Mapping JSON response to Java POJO Class using GSON

。_饼干妹妹 提交于 2019-12-25 03:57:33

问题


I am trying to map below JSON to a POJO Class using Gson library. Below is the JSON response and POJO Class and mapping done

import java.util.Map;

import com.google.gson.JsonElement;

public class DataResponse {

    private String $status;
    private Map<String, JsonElement> $payload;

    public String get$status() {
        return $status;
    }

    public void set$status(String $status) {
        this.$status = $status;
    }

    public Map<String, JsonElement> get$payload() {
        return $payload;
    }

    public void set$payload(Map<String, JsonElement> $payload) {
        this.$payload = $payload;
    } 
}

Here is the Sample JSON.

{
  "$status": "OK",
  "$payload": {
    "$nextStart": "123",
    "$results": [
      {
        "$key": "101",
        "score": 3,
        "to": "Test1"
      },
      {
        "$key": "102",
        "score": 4,
        "to": "Test2"
      },
    ]
  }
}

Below is the mapping done. Is there some problem with POJO class definition. Since I cannot get all the elements of JSON response mapped to the innermost element from the response. Appreciate your support in providing useful suggestions.

Gson gson = new Gson();
                        DataResponse dataResponse = gson.fromJson(EntityUtils.toString(response.getEntity()),
                                DataResponse.class);

回答1:


While working with marshalling and unmarshalling, it is always good to have a model defined as:

public class DataResponse {

    private String $status;
    private Payload $payload;
   // getters and setters
}

class Payload {
    private String $nextStart;
    private List<Result> $results;

    // getters and setters
}


class Result {
    private String $key;
    private String score;
    private String to;

    // getters and setters
}

Now when you convert json to POJO as:

Gson gson = new Gson(); 
DataResponse dataResponse = gson.fromJson(EntityUtils.toString(response.getEntity()), DataResponse.class);

it can easily convert it.

Also, believe me, it is good for processing in your further code!

Update: if you really want to convert json to Map, then you can do something like this:

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;

Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson("{'key':'value'}", type);

Substitute json string there.



来源:https://stackoverflow.com/questions/52750818/mapping-json-response-to-java-pojo-class-using-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!