如何在java中使用json获取10个数据

时间:2011-03-06 20:42:59

标签: java json

您好 我从db获得了大约10个数据,属性名称相同

 JSONObject json = new JSONObject();
 json.put("text",value1);
 json.put("title",value2);
 json.put("url",value3);

我使用上面的代码,我变得与此类似

 {"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"}
 {"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"}
 {"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"}
 {"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"}

当我在php中解析它时我得到一个空值我不知道y ..你能告诉我我错在哪里......

2 个答案:

答案 0 :(得分:2)

你的输出应该是这样的可解析的

 [{"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"},
 {"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"},
 {"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"},
 {"text":"texting is not bad","title":"tesing","url":"http:\/\/www.example.com\/"}]

为此你应该使用JSONArray

答案 1 :(得分:1)

基本上你必须创建一个JSON数组来保存你的10个数据,如下所示:

JSONArray jsonArray = new JSONArray();
for (int i = 0; i < 10; i++) {
    JSONObject json = new JSONObject();
    json.put("text",value1);
    json.put("title",value2);
    json.put("url",value3);
    jsonArray.put(json);
}

输出,请参阅Bala R的回复。