以下是使用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;
}
杰克逊实施例:
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));
}
}
也许你可以包括POJO定义你没有尝试,给什么可能出现了问题的想法?基本想法只是为了匹配结构。 – StaxMan
此外,发布问题时,我建议尽力确保任何代码或JSON示例的有效性和正确性。原始问题中的JSON示例无效,可能会帮助或从此线程中学习猜测什么是什么的人。可以使用http://jsonlint.com快速,轻松地验证JSON。 –