【问题标题】:String converted JSON Object is not proper while using JSONArray.put(JSONObject)使用 JSONArray.put(JSONObject) 时字符串转换的 JSON 对象不正确
【发布时间】:2016-02-09 07:38:52
【问题描述】:
String dummyStr="[{\"Emp_Id\":\"1254\",\"Emp_Name\":\"abcd\"},{\"Emp_Id\":\"1234\",\"Emp_Name\":\"efgh\"}]";

System.out.println("The JSON string is"+dummyStr);

给出以下输出:

JSON 字符串为 [{"Emp_Id":"1254","Emp_Name":"abcd"},{"Emp_Id":"1234","Emp_Name":"efgh"}]

****但是当我尝试放入一个数组列表时,它显示为****

tmpJsonArrayList.put(dummyStr)

System.out.println("The JSON string  List  is"+tmpJsonArrayList);

JSON 字符串列表为["[{\"Emp_Id\":\"1254\",\"Emp_Name\":\"abcd\"},{\"Emp_Id\":\"1234\", \"Emp_Name\":\"efgh\"}]"]

【问题讨论】:

  • 您能否详细说明您想要实现的目标?另外一点代码可能会有所帮助。 tmpJsonArrayList 是一个什么样的列表?

标签: java json string


【解决方案1】:

您可以使用 JsonParser 将字符串转换为 json 数组:

    String dummyStr="[{\"Emp_Id\":\"1254\",\"Emp_Name\":\"abcd\"},{\"Emp_Id\":\"1234\",\"Emp_Name\":\"efgh\"}]";

    JsonParser parser = new JsonParser();
    // parse the string as JsonArray
    JsonArray tmpJsonArrayList = (JsonArray) parser.parse(dummyStr);


    System.out.println("The JSON string List is"+tmpJsonArrayList);

【讨论】:

    【解决方案2】:
    String dummyStr="[{\"Emp_Id\":\"1254\",\"Emp_Name\":\"abcd\"},{\"Emp_Id\":\"1234\",\"Emp_Name\":\"efgh\"}]";
    
    JsonParser parser =  new JsonParser();
    JsonElement jsonElement = parser.parse(dummyStr);
    JsonArray tmpJsonArrayList = jsonElement.getAsJsonArray();
    System.out.println("The JSON string List is"+tmpJsonArrayList);
    

    这就是我们在java中解析json字符串的方法。您需要添加com.google.gson 库来编译此代码。

    【讨论】:

      猜你喜欢
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 2013-01-10
      • 1970-01-01
      • 2016-09-18
      • 2018-05-03
      相关资源
      最近更新 更多