使用GSON将JSON响应映射到Java POJO类 [英] Mapping JSON response to Java POJO Class using GSON

查看:106
本文介绍了使用GSON将JSON响应映射到Java POJO类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Gson库将JSON以下映射到POJO类.下面是JSON响应和POJO类以及已完成的映射

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;
    } 
}

这是示例JSON.

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

下面是完成的映射. POJO类定义是否存在一些问题.由于我无法将JSON响应的所有元素都映射到响应中最里面的元素.感谢您提供有用建议的支持.

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);

推荐答案

在进行编组和解组时,最好将模型定义为:

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
}

现在,当您将json转换为POJO时:

Now when you convert json to POJO as:

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

它可以轻松转换.

另外,请相信我,这对于处理进一步的代码非常有用!

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

更新:如果您真的想将json转换为Map,则可以执行以下操作:

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);

在那里替换json字符串.

Substitute json string there.

这篇关于使用GSON将JSON响应映射到Java POJO类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆