如何正确地从Java产生JSONArray? [英] How to generate JSONArray properly from Java?

查看:101
本文介绍了如何正确地从Java产生JSONArray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图生成使用Java那种JSON字符串的(目的:海军报为Android):

I'm trying to generate that kind of JSON String using Java (purpose : flot for Android) :

{
"data": [[1999, 1], [2000, 0.23], [2001, 3], [2002, 4], [2003, 1.3], [2004, 2.5], [2005, 2.0], [2006, 3.1], [2007, 2.9], [2008, 0.9]]
}

要做到这一点,我使用JSONArray是这样的:

To do this, I'm using JSONArray like this :

JSONArray jsonArray = new JSONArray();
jsonArray.put("[1999, 1]");
jsonArray.put("[2000, 0.23]");
jsonArray.put("[2001, 3]");
...

但唯一的结果我得到的是这样的:

But the only result I get is this :

["[1999, 1]","[2000, 0.23]","[2001, 3]",..."[2008, 0.9]"]

我如何删除括号中的报价?我可以输入我的数组的项目?

How Can I remove quote between brackets ? Can I type the items of my array ?

在此先感谢!

推荐答案

你在做什么只是添加到字符串数组。你不想字符串,你要嵌套数组。所以,你必须使用嵌套JSONArray对象工作:

What you are doing is just adding Strings to the array. You don't want Strings, you want nested arrays. So you have to work with nested JSONArray objects:

下面是标准方式:

JSONArray nested1 = new JSONArray();
nested1.put(1999);
nested1.put(1);
jsonArray.put(nested1);

或者<一个href=\"http://www.json.org/javadoc/org/json/JSONArray.html#JSONArray%28java.util.Collection%29\">simpler:

jsonArray.put(new JSONArray(Arrays.asList(1999, 1)));

或者,更简单

jsonArray.put(Arrays.asList(1999, 1));
// or use an int array:
jsonArray.put(new int[]{1999, 1});

这篇关于如何正确地从Java产生JSONArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆