gpt4 book ai didi

java - Android 中的 GSON/Jackson

转载 作者:太空宇宙 更新时间:2023-11-03 12:11:48 26 4
gpt4 key购买 nike

我能够使用 JSONObject 和 JSONArray 在 Android 中成功解析以下 JSON 字符串。使用 GSON 或 Jackson 没有成功取得相同的结果。有人可以帮我处理包括 POJO 定义在内的代码 fragment ,以便用 GSON 和 Jackson 解析它吗?

{
"response":{
"status":200
},
"items":[
{
"item":{
"body":"Computing"
"subject":"Math"
"attachment":false,
}
},
{
"item":{
"body":"Analytics"
"subject":"Quant"
"attachment":true,
}
},

],
"score":10,
"thesis":{
"submitted":false,
"title":"Masters"
"field":"Sciences",
}
}

最佳答案

以下是使用 Gson 和 Jackson 将 JSON(类似于原始问题中的无效 JSON)与匹配的 Java 数据结构反序列化/序列化的简单示例。

JSON:

{
"response": {
"status": 200
},
"items": [
{
"item": {
"body": "Computing",
"subject": "Math",
"attachment": false
}
},
{
"item": {
"body": "Analytics",
"subject": "Quant",
"attachment": true
}
}
],
"score": 10,
"thesis": {
"submitted": false,
"title": "Masters",
"field": "Sciences"
}
}

匹配的 Java 数据结构:

class Thing
{
Response response;
ItemWrapper[] items;
int score;
Thesis thesis;
}

class Response
{
int status;
}

class ItemWrapper
{
Item item;
}

class Item
{
String body;
String subject;
boolean attachment;
}

class Thesis
{
boolean submitted;
String title;
String field;
}

jackson 示例:

import java.io.File;

import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonFoo
{
public static void main(String[] args) throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibilityChecker(
mapper.getVisibilityChecker()
.withFieldVisibility(Visibility.ANY));
Thing thing = mapper.readValue(new File("input.json"), Thing.class);
System.out.println(mapper.writeValueAsString(thing));
}
}

Gson 示例:

import java.io.FileReader;

import com.google.gson.Gson;

public class GsonFoo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
Thing thing = gson.fromJson(new FileReader("input.json"), Thing.class);
System.out.println(gson.toJson(thing));
}
}

关于java - Android 中的 GSON/Jackson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7939632/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com