使用GSON将JSON响应映射到Java POJO类

编程入门 行业动态 更新时间:2024-10-27 09:33:34
本文介绍了使用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类

本文发布于:2023-08-01 09:11:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1267150.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JSON   GSON   POJO   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!