You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Gson将JsonObject解析为UserDetails实体类的技术问询

How to Parse JSON to Your UserDetails Class Using Gson

Let's walk through the steps to correctly map your server's JSON response to the UserDetails class you've defined. Here's what you need to do:

1. Align Your Class with JSON Key Names

Gson matches JSON keys to your class's fields (or constructor parameters) by default. If your server uses different key names than your fields (e.g., lowercase id instead of ID, or userEmail instead of user_email), use @SerializedName annotations to bridge the gap.

Option A: Annotate Class Fields

import com.google.gson.annotations.SerializedName;

public class UserDetails {
    @SerializedName("id") // Replace with your actual JSON key for the ID
    private final int ID;
    @SerializedName("user_email") // Match the JSON key for the email
    private final String user_email;

    public UserDetails(int ID, String user_email) {
        this.ID = ID;
        this.user_email = user_email;
    }

    public int getID() { return ID; }
    public String getUser_email() { return user_email; }
}

Option B: Annotate Constructor Parameters

If you prefer not to mark up fields, apply @SerializedName directly to the constructor parameters:

import com.google.gson.annotations.SerializedName;

public class UserDetails {
    private final int ID;
    private final String user_email;

    public UserDetails(@SerializedName("id") int ID, @SerializedName("user_email") String user_email) {
        this.ID = ID;
        this.user_email = user_email;
    }

    public int getID() { return ID; }
    public String getUser_email() { return user_email; }
}

2. Parse the JSON in Your onResponse Method

Once your class is set up, use Gson's fromJson() method to convert the raw JSON string into a UserDetails instance. Here's how to update your code:

import com.google.gson.Gson;

public void onResponse(Call call, Response response) throws IOException {
    if (response.isSuccessful() && response.body() != null) {
        String mMessage = response.body().string();
        
        // Initialize Gson
        Gson gson = new Gson();
        
        // Parse directly to UserDetails if the JSON is a single user object
        UserDetails userDetails = gson.fromJson(mMessage, UserDetails.class);
        
        // Use the parsed object
        System.out.println("User ID: " + userDetails.getID());
        System.out.println("User Email: " + userDetails.getUser_email());
    } else {
        // Handle unsuccessful responses
        System.err.println("Request failed with code: " + response.code());
    }
}

3. Handle Wrapped JSON Responses

If your server returns a JSON object that wraps the user details (e.g., {"user": {"ID": 1, "user_email": "test@example.com"}}), create a wrapper class to match the structure:

// Wrapper class for the outer JSON object
public class UserResponse {
    private UserDetails user; // Match the wrapper key from your JSON
    
    public UserDetails getUser() { return user; }
}

Then adjust the parsing code:

UserResponse userResponse = gson.fromJson(mMessage, UserResponse.class);
UserDetails userDetails = userResponse.getUser();

Key Tips

  • Ensure you have the Gson dependency added to your project (e.g., for Gradle: implementation 'com.google.code.gson:gson:2.10.1').
  • Always validate the response success and non-null body before parsing to avoid exceptions.
  • Gson will automatically use your constructor since all fields are final and parameters align with mapped JSON keys.

内容的提问来源于stack exchange,提问作者Tunga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:50:21