我想连接多个json对象。
我有两个这样的json
{"message":"test","status":"0"}
和这个
{"message":"test-2","status":"1"}
结果必须是
[{"message":"test","status":"0"},{"message":"test-2","status":"1"}]
我怎样才能用Java做到这一点?
答案 0 :(得分:4)
您可以轻松使用JSONObject.toString()
并轻松连接字符串
e.g
String x = "[" + obj1.toString() "," + obj2.toString() + "]";
或
StringBuilder newStr = new StringBuilder() ;
newStr.append("[").append(obj1.toString()).append(",").append(obj2.toString());
答案 1 :(得分:3)
做这样的事情:
List<String> array = new ArrayList<String>();
array.add("{\"message\":\"test\",\"status\":\"0\"}");
array.add("{\"message\":\"test-2\",\"status\":\"1\"}");
array.toString();
如果您想在Java中使用对JSON对象的支持,请考虑使用Gson:
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Main {
public static void main(String[] args) {
JsonObject json1 = (JsonObject) new JsonParser().parse("{\"message\":\"test\",\"status\":\"0\"}");
JsonObject json2 = (JsonObject) new JsonParser().parse("{\"message\":\"test-2\",\"status\":\"1\"}");
JsonArray array = new JsonArray();
array.add(json1);
array.add(json2);
System.out.println(array.toString());
}
}
这次会给你你想要的对象。
答案 2 :(得分:0)
private static void concatJSON() throws IOException, InterruptedException {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(new File(Main.class.getResource("/file/user.json").toURI())));
JSONObject jsonObj = (JSONObject) obj; //usernameJsonObj
String [] values = {"0.9" , Date.from(Calendar.getInstance().toInstant()).toLocaleString()},
innermost = {"Accomplished", "LatestDate"},
inner = {"Lesson1", "Lesson2", "Lesson3", "Lesson4"};
String in = "Jayvee Villa";
JSONObject jo1 = new JSONObject();
for (int i = 0; i < innermost.length; i++)
jo1.put(innermost[i], values[i]);
JSONObject jo2 = new JSONObject();
for (int i = 0; i < inner.length; i++)
jo2.put(inner[i], jo1);
JSONObject jo3 = new JSONObject();
jo3.put(in, jo2);
String merger = jsonObj.toString().substring(0, jsonObj.toString().length()-1) + "," +jo3.toString().substring(1);
System.out.println(merger);
FileWriter pr = new FileWriter(file);
pr.write(merger);
pr.flush();
pr.close();
}