[英]JSON Parsing using Jackson/Gson Java
I have the following Json 我有以下杰森
{
"messages":[
{
"message":{
"body":"Foo",
"username":"XYZ"
}
},
{
"message":{
"body":"HI",
"username":"ABC"
}
}
],
"response":{
"status":200
},
"more":true
}
I build Custom classes My container class Result holds a List objects a Response object which contains a status and a boolean. 我构建自定义类我的容器类Result包含一个List对象和一个Response对象,其中包含一个状态和一个布尔值。
public class Message {
@SerializedName("body")
public String body;
@SerializedName("username")
public String username;
@Override public String toString() {
return "Message{" + "body=" + body + ", username=" + username + '}';
}
}
public class Response {
public int status;
}
public class SearchResponseST {
@SerializedName("messages")
public Message[] messages;
public Response response;
public boolean more;
}
In my main class I do: 在我的主要课程中,我这样做:
SearchResponseST response =
gson.fromJson(reader, SearchResponseST.class); Message[] results = response.messages;
If I eliminate the "message": and start the array directly, I am able to deserialize successfully using Gson. 如果消除“消息”:并直接启动数组,则可以使用Gson成功反序列化。
How should I be parsing it with the current structure? 我应该如何用当前结构来解析它?
Though this does not answer your question directly, because I do not use Gson. 尽管这不能直接回答您的问题,因为我不使用Gson。 I have always used the org.json.simple package to parse JSSON.
我一直使用org.json.simple包来解析JSSON。 you can read about it here: http://www.mkyong.com/java/json-simple-example-read-and-write-json/ Just throw the JSON into the parser, and get the data you want out.
您可以在此处阅读有关内容: http : //www.mkyong.com/java/json-simple-example-read-and-write-json/只需将JSON放入解析器中,然后获取所需的数据即可。 Data is accessed just like you would access a HashMap (for JSONObject) or ArrayList (for JSONArray).
就像访问HashMap(对于JSONObject)或ArrayList(对于JSONArray)一样,访问数据。
EDIT with parsing code: 使用解析代码进行编辑:
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(new FileReader("file.txt"));
JSONArray array = (JSONArray) obj.get("messages");
for (Object o : array) {
JSONObject jo =(JSONObject)o;
JSONObject messageObject = (JSONObject)jo.get("message");
System.out.println(messageObject.get("body"));
System.out.println(messageObject.get("username"));
}
For a JSON like this 对于这样的JSON
{
"messages":
[
{"body": "Foo", "username": "XYZ" },
{"body": "HI", "username": "ABC" }
],
"response": {"status": 200 },
"more": true
}
try Container object designed like 尝试将容器对象设计为
Container { List<Message> messages;Response response;boolean more;}
BUT for the JSON you have posted, the Container object should be 但是对于您发布的JSON,Container对象应为
Container { public HashMap[] messages; public boolean more; public Response response; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.