以下是使用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。 –