[英]How to get the values from keys in nested objects using only json-simple
I want to get only a specific value out of all the nested objects. 我想从所有嵌套对象中只获取一个特定值。 In the application I just need the msg 3 which is inside another object messages. 在应用程序中,我只需要在另一个对象消息中的msg 3。
I have tried it using JSONObject but it is not working for nested object. 我已经尝试使用JSONObject,但它不适用于嵌套对象。 However It is working with just a single object means root object . 然而,只使用单个对象就意味着根对象。
INPUT - {"name":"lola","messages":{"msg 1":"msg 2","msg 3":"msg 4"},"age":22}
String s = sc.nextLine();
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(s);
System.out.println(json);
Object name = json.get("messages");
System.out.println(name);
JSONObject messageObject = (JSONObject) json.get("messages");
System.out.println(employeeObject);
//Get employee first name
String msg= (String) messageObject.get("msg3");
System.out.println(msg);
The Output: 输出:
{"msg 3":"msg 4","msg 1":"msg 2"}
{"msg 3":"msg 4","msg 1":"msg 2"}
null
The last nested object is not fetching in any way. 最后一个嵌套对象不以任何方式获取。 Another thing is that the normal print of the string as a JSONObject gets changed. 另一件事是作为JSONObject的字符串的正常打印得到改变。 like the msg3 came before msg1. 就像msg3在msg1之前出现一样。 In place of null - msg4 should be there. 代替null - msg4应该在那里。
Thanks in advance. 提前致谢。
You are missing a space between "msg" and "3". 您错过了“msg”和“3”之间的空格。 By the way - you can do this easier, as such. 顺便说一下 - 你可以这样做更容易。
String s = sc.nextLine();
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(s);
System.out.println(json);
System.out.println(json.get("message").get("msg 3"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.