1

I'm trying to use GSON 2.2.2 (for the very first time) to map JSON into a Java POJO. I'm hitting a 3rd party RESTful web service and this is an example of the JSON I'm getting back:

{
    "response": {
        "job":{
            "eta":-1,
            "status":"approved",
            "mt":1,
            "lc_tgt":"fr",
            "body_src":"Please translated me.",
            "body_tgt":"S'il vous plaît traduire moi.",
            "unit_count":3,
            "tier":"machine",
            "credits":0,
            "ctime":"2013-02-07 14:56:12.391963",
            "lc_src":"en",
            "slug":"0",
            "job_id":"NULL"
        }
    },
    "opstat":"ok"
}

The POJO I'm trying to map this into is:

public class Job {
    // correlates to "eta"
    private int eta;

    // correlates to "body_src"
    private String sourceBody;

    // correlates to "ctime"
    private java.util.Date creationTimestamp;

    // Getters and setters for all 3 properties
}

When I run the following code, I don't get any exceptions, but the print statement just prints "null":

// Hit the 3rd party service and get the JSON (example above).
JSONObject json = hitRestfulWebService();

Gson gson = new Gson();

// json.toString = "{response":{"job":{ ..."
Job job = gson.fromJson(json.toString(), Job.class);

System.out.println(job.getSourceBody());

My only guess is that GSON can't figure out how to map the 3 JSON fields to my 3 Job properties. Can someone help me figure out what this mapping needs to be? Thanks in advance.

4

3 回答 3

3

您可以使用注释来定义,哪个 json 字段映射到哪个对象成员,例如:

class SomeClass
{
   @SerializedName("body-src")
   String myString1;

   @SerializedName("header-src")
   String myString2;
...
于 2013-02-07T15:52:24.380 回答
1

不使用响应,而是使用 response.job

不是

  {   "response": {..

利用

 { "eva": ..

这可能会有所帮助;

    String a = "{\"response\": {\"job\":{\"eta\":-1,\"status\":\"approved\",\"mt\":1,\"lc_tgt\":\"fr\",\"body_src\":\"Please translated me.\",\"body_tgt\":\"S'il vous plaît traduire moi.\",\"unit_count\":3,\"tier\":\"machine\",\"credits\":0,\"ctime\":\"2013-02-07 14:56:12.391963\",\"lc_src\":\"en\",\"slug\":\"0\",\"job_id\":\"NULL\"}},\"opstat\":\"ok\"}";



    Job j = I.gson().fromJson(
            ((JsonObject) ((JsonObject) new JsonParser().parse(a)).get("response")).get("job"), Job.class);

    System.out.println(j.getEta());
于 2013-02-07T15:20:41.780 回答
1
public class Response{
  private Job job;

  //generate setter and getter
}

public class Job {
    // correlates to "eta"
    private int eta;

    // correlates to "body_src"
    private String sourceBody;

    // correlates to "ctime"
    private java.util.Date creationTimestamp;

    // Getters and setters for all 3 properties
}

现在在格森

JSONObject json = hitRestfulWebService();

Gson gson = new Gson();

// json.toString = "{response":{"job":{ ..."
Job job = gson.fromJson(json.toString(), Response.class);
于 2013-02-07T15:46:39.700 回答