这是我的JSON字符串我使用我的java代码[result]成功加载。
{"result":[
{
"opened_at":"2017-02-06 10:48:55",
"sys_updated_by":"user",
"state":"6"
},
{
"opened_at":"2017-02-06 12:20:43",
"sys_updated_by":"user2",
"state":"1"
},
{
"opened_at":"2017-02-06 15:32:34",
"sys_updated_by":"user3",
"state":"1"
}
]
}
这是我将JSON数据保存在JSONArray中的部分。
JSONArray arr = obj.getJSONArray("result");
for (int i = 0; i < arr.length(); i++) {
String opened_at = arr.getJSONObject(i).getString("opened_at");
String sys_updated_by = arr.getJSONObject(i).getString("sys_updated_by");
String state = arr.getJSONObject(i).getString("state");
}
如何从控制台中的user2打印例如opens_at(使用System.out.println())?
答案 0 :(得分:0)
你几乎就在那里,在for
循环中,你只需要检查sys_updated_by
的值并获得opened_at
的相应值:
JSONArray arr = obj.getJSONArray("result");
String opened = null;
for (int i = 0; i < arr.length(); i++) {
String sys_updated_by = arr.getJSONObject(i).getString("sys_updated_by");
if("user2".equals(sys_updated_by)){
opened = arr.getJSONObject(i).getString("opened_at");
break; //No need to iterate anymore
}
}
System.out.println(opened);
答案 1 :(得分:0)
使用for-each loop
时非常简单,然后检查user2
opened_at
存储值 String openedAt = "";
for(JOSNObject object : arr){
if(object.getString("sys_updated_by").equals("user2")){
openedAt = object.getString("opened_at");
break;
}
}
System.out.println(openedAt);
是否为某些字符串并突破厕所。
try
{ // Open the text file using a stream reader.
using (StreamReader sr = new StreamReader("dynamic.js"))
{
// Read the stream to a string, and write the string to the console.
dynamicJS = sr.ReadToEnd();
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
// user has been authenticated return data and JS to the front end
return $"{{ \"Email\": \"{userDetails.Email}\", \"DisplayName\": \"{userDetails.DisplayName}\", \"Services\": {safeServices.SerializeToJsonString()}, \"PageElements\": \"{pageURLs}\", \"DyanamicJS\": \"{dynamicJS}\" }}";
答案 2 :(得分:0)
如何从user2访问例如opens_at?
java.util.Map<String , Object> myMap = new java.util.HashMap<>();
for (int i = 0; i < arr.length(); i++) {
String opened_at = arr.getJSONObject(i).getString("opened_at");
String sys_updated_by = arr.getJSONObject(i).getString("sys_updated_by");
String state = arr.getJSONObject(i).getString("state");
// your CATCH
myMap.put( sys_updated_by , arr.getJSONObject(i) );
}
// IF YOUR ARE HARDCODING ACCESS
try
{
System.out.println( ( (JSONObject)myMap.get("user") ).getString("opened_at") + ((JSONObject)myMap.get("user2")).getString("opened_at") );
}
catch(Exception any){}
让sys_update_by键值,成为所有感兴趣字段的JSONObject引用的键,然后让它帮助您检索您感兴趣的记录,只需在哈希映射中指定用户名,对不起百万更新,我一定想讨论这不是你正在寻找的答案