为什么将元素放入JSONArray之后将它们混合?

时间:2018-12-14 16:13:58

标签: java

使用StringBuilder遇到问题。我需要在JSONArray中放置一个StringBuilder,但是当我这样做时,我的字符串会被随机播放。我该如何解决?

我之前的电话:

[{"id":"iprod","name":"soup","categoryId":"categoryId123","categoryName":"soup","imageUrl":"c/image","price":5.0,"weight":123.0,"ingredients":["chicken","rice"],"nutrition":{"energy":{"kilojoules":123,"kilocalories":123},"fat":123,"carbohydrate":123,"protein":123},"currency":"123"}]

我之后的一行:

[{"nutrition":{"protein":123,"fat":123,"carbohydrate":123,"energy":{"kilojoules":123,"kilocalories":123}},"price":5,"imageUrl":"c/image","name":"soup","weight":123,"ingredients":["chicken","rice"],"currency":"123","id":"iprod","categoryName":"soup","categoryId":"categoryId123"}]

代码:

StringBuilder sb = new StringBuilder();

String line;
while ((line = br.readLine()) != null) {
    sb.append(line);
}

br.close();

System.out.println(sb.toString());
JSONArray responseObject = new JSONArray(sb.toString());
System.out.println(responseObject.get(0));

1 个答案:

答案 0 :(得分:1)

您的字符串是JSONObject而不是JSONArray

摘自http://www.json.org/的JSON规范

  

一个对象是一组无序的   名称/值对

JSON库可以自由地按其认为合适的方式重新排列元素的顺序。 GSON,由Google开发的Java库,用于处理JSON。它将为您保存订单:

这是代码:

import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class Test {

    public static void main(String[] args) {
        Gson gson = new Gson();

        String line = "{\"id\":\"iprod\",\"name\":\"soup\",\"categoryId\":\"categoryId123\",\"categoryName\":\"soup\",\"imageUrl\":\"c/image\",\"price\":5.0,\"weight\":123.0,\"ingredients\":[\"chicken\",\"rice\"],\"nutrition\":{\"energy\":{\"kilojoules\":123,\"kilocalories\":123},\"fat\":123,\"carbohydrate\":123,\"protein\":123},\"currency\":\"123\"}\n";

        System.out.println(line);
        JsonObject responseObject = gson.fromJson(line, JsonObject.class);
        System.out.println(responseObject.keySet());

    }

}