如何阻止 JSONObject 将我的 ArrayList [3,4] 转换为字符串 “[3,4]”

huangapple go评论55阅读模式
英文:

How to stop JSONObject to convert my arrayList [3,4] in string "[3,4]"

问题

这是代码部分

JSONObject myJson = new JSONObject();

try {
   List<Integer> myLists = new ArrayList<>();
   myLists.add(4);
   myLists.add(10);

   myJson.put("myLists", myLists);
} catch (JSONException e) {
    e.printStackTrace();
}

Log.w("myJson", myJson);


这是控制台输出

"myJson":"[4, 10]";


这是我想要的控制台输出

"myJson":[4, 10]                 注意数组周围没有引号 ""
英文:

1)This is the Code:

JSONObject myJson=new JSONObject();

try {

   List&lt;Integer&gt; myLists = new ArrayList&lt;&gt;();
   myLists.add(4);
   myLists.add(10);

   myJson.put(&quot;myLists&quot;,myLists);

} catch (JSONException e) {
        e.printStackTrace();
}

Log.w(&quot;myJson&quot;, myJson);

2)This is the output in the console:

&quot;myJson&quot;:&quot;[4, 10]&quot;

2)This is what I want in the console:

&quot;myJson&quot;:[4, 10]                 (note the absence of quote &quot;&quot; around the array)

答案1

得分: 2

只需使用:

myJson.put("myLists", new JSONArray(myLists));

否则,如果您传递ArrayList或List,这将被识别为Object,而不是类似Array的内容,因此将使用toString()方法将其放入JSON中。

英文:

Just use:

        myJson.put(&quot;myLists&quot;, new JSONArray(myLists));

Otherwise, if you pass ArrayList, or List this will be recognized as Object, not as something like Array, so toString() method will be used for putting it in JSON.

huangapple
  • 本文由 发表于 2020年8月22日 01:34:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63527555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定