我有一个Json数组,在每个对象上我想相应地编辑特定键的值
例如,我如何循环遍历此数组并编辑" unix_time"每个对象的关键。
[{"_id":"","__v":0,"read":false,"timestamp":"","unix_time":"1477924542020"},
{"_id":"","__v":0,"read":false,"timestamp":"","unix_time":"1477924542020"},
{"_id":"","__v":0,"read":false,"timestamp":"","unix_time":"1477924532440"},
...
...
... ]
答案 0 :(得分:1)
以下是测试类。如果有帮助,请告诉我
package com.test;
import org.json.JSONArray;
import org.json.JSONObject;
public class JSONTest {
public static void main(String[] args){
JSONArray jsonArray = new JSONArray();
JSONObject j1 = new JSONObject();
j1.put("id", "1");
j1.put("read", "false");
j1.put("time", "143250176");
jsonArray.put(j1);
JSONObject j2 = new JSONObject();
j2.put("id", "2");
j2.put("read", "false");
j2.put("time", "143250177");
jsonArray.put(j2);
JSONObject j3 = new JSONObject();
j3.put("id", "3");
j3.put("read", "false");
j3.put("time", "143250178");
jsonArray.put(j3);
JSONArray newArray = new JSONArray();
for(int count=0; count<jsonArray.length(); count++)
{
JSONObject localInstance = jsonArray.getJSONObject(count);
if(localInstance.optString("time") != "")
{
String time = localInstance.getString("time");
String newTime = "new "+time;
localInstance.put("time", newTime);
newArray.put(localInstance);
}
}
System.out.println(newArray);
}
}
答案 1 :(得分:0)
尝试:
public class TransfomerService
{
MessageXTransformer messageXTransformer = new MessageXTransformer();
MessageYTransformer messageYTransformer = new MessageYTransformer();
public CanonicalMessage transform(VendorMessage message)
{
if (message instanceOf MessageA)
{
return messageXTransformer.transform((MessageA) message);
}
else if (message instanceOf MessageB)
{
return messageYTransformer.transform((MessageB) message);
}
}
}