Mapping JSON response to Java POJO Class using GSO

2019-08-21 08:52发布

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条回答
成全新的幸福
2楼-- · 2019-08-21 09:34

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.

查看更多
登录 后发表回答