【问题标题】:Converting string array into json将字符串数组转换为json
【发布时间】:2014-07-07 06:30:20
【问题描述】:

我的字符串数组每次遍历循环时都有以下输出

apple
orange

我想将我的字符串数组输出转换为 json 格式/jsonarray。我试过了,但它给出的输出为

{"fruits",apple}
{"fruits",orange}

我希望我的输出为

{"fruits": [
{

  "1": "apple"
}
{

  "2": "orange"
}

我试过下面的代码

String[] strArray = new String[] {newString};
        JSONObject json=new JSONObject();
        //json.put("fruits", newString);

       //System.out.println(json);
        for(int i=0;i<strArray.length;i++)
        {
            System.out.print(strArray[i]+"\t");
               json.put("",strArray[i]);

        }

【问题讨论】:

    标签: java json arrays


    【解决方案1】:
      JSONObject obj = new JSONObject();
      JSONArray array = new JSONArray();
      for(int i=0;i<strArray.length;i++)
        {
            JSONObject fruit = new JSONObject();
            fruit.put(""+i,strArray[i]); 
            array.put(fruit);
        }
       obj.put("Fruits",array);
       System.Out.Println(obj.toString(2));
    

    【讨论】:

      【解决方案2】:

      试试下面的代码:-

      JsonObject jsonObject = new JsonObject();
      jsonObject.addProperty("key", "value");
      String jsonString = jsonObject.toString();
      

      我希望这对你有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-27
        • 2013-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多