【问题标题】:want to store multiple JSON objects to jsonArray and get the result as a single string想要将多个 JSON 对象存储到 jsonArray 并将结果作为单个字符串获取
【发布时间】:2020-04-09 15:37:45
【问题描述】:

这是我将多个 JSON 对象存储到数组中的代码,然后我想将数组转换为单个字符串。

String message =null;
JSONObject json = new JSONObject();
json.put("name","student");
json.put("name", "Atal");
json.put("name","Rachit");


JSONArray array = new JSONArray();
for(int i= 0; i<= array.length(); i++) {    
    array.put(json);
    message = array.toJSONString();
}

我想将输出作为字符串存储在消息变量中。

【问题讨论】:

  • 每次调用 json.put() 时,您都在替换 name。你能发布一个你想打印的示例输出吗?
  • 感谢它的工作。每次我调用 json.put() 时,我实际上都是在替换 name 。

标签: java json


【解决方案1】:

我每次调用 json.put() 时都会替换“名称”

String message =null;
JSONObject json = new JSONObject();
json.put("name","Atal");
json.put("class", "10");
json.put("Roll","1035");


JSONArray array = new JSONArray();

array.put(json);
message = array.toJSONString();

【讨论】:

    【解决方案2】:
    String message =null;
    JSONObject json = new JSONObject();
    json.put("name","student");
    json.put("name", "Atal");
    json.put("name","Rachit");
    
    
    JSONArray array = new JSONArray();
    //for(int i= 0; i<= array.length(); i++) {    
    //    array.put(json);
    //    message = array.toJSONString();
    //}
    array.put(json); //There is a JSON,just put it into the array
    message = array.toJSONString();
    
    

    【讨论】:

    • 这样,它只会将最后一个 json.put("name","Rachit") 存储在数组中,但我想将所有三个 json.put 语句存储在数组中。跨度>
    猜你喜欢
    • 2016-10-19
    • 1970-01-01
    • 2019-01-25
    • 1970-01-01
    • 2013-06-09
    • 2016-09-05
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    相关资源
    最近更新 更多