如何在Json数组中创建Json数组?

时间:2016-02-11 05:27:05

标签: java android arrays json

这是我尝试解析的服务器

    [
  {
   "Hello": "How are You?",
"GoodBye": "I will see you later",
"Today": "How is it outside today",
"Date": "what is the date today",
"Weather": "10 degrees",
"Subcategory": [
  {
    "text": "Text goes here",
          }
{
    "text": "Text goes here",
          }
{
    "text": "Text goes here",
          }]
  [
  {
   "Hello": "How are You?",
"GoodBye": "I will see you later",
"Today": "How is it outside today",
"Date": "what is the date today",
"Weather": "10 degrees",
"Subcategory2": [
{
    "text": "Text goes here",
          }
{
    "text": "Text goes here",
          }
{
    "text": "Text goes here",
          }]
  [

另外,下面我单独对文本进行了JSON解析,但是,我想得到天气的文字。

2 个答案:

答案 0 :(得分:1)

text密钥位于Subcategory JSONArray内,因此需要首先获取JSONArray,然后从中获取text字符串:

JSONObject currentQuestions = response.getJSONObject(x);
JSONArray arrSubcategory=currentQuestions.optJSONArray("Subcategory");
for (int y = 0; y < arrSubcategory.length(); y++) {
   JSONObject objectSubcategory = arrSubcategory.getJSONObject(y);
   String text = objectSubcategory.optString("text");
}

注意:

如果Subcategory JSONArray键名称是动态的,如Subcategory,Subcategory1,...,那么请执行以下操作:

JSONObject currentQuestions = response.getJSONObject(x);
Iterator<String> iter = currentQuestions.keys();
while (iter.hasNext()) {
    String key = iter.next();
    JSONArray arrSubcategory=currentQuestions.optJSONArray(key);
    for (int y = 0; y < arrSubcategory.length(); y++) {
       JSONObject objectSubcategory = arrSubcategory.getJSONObject(y);
       String text = objectSubcategory.optString("text");
    }
}

答案 1 :(得分:0)

就这样做。

JSONArray array=new JSONArray(Your JSONObject);

现在上面是主JSONArray。

JSONArray newArray=new JSONArray();
for(int i=0;i<array.length();i++){
 JSONObject objmain=array.getJSONObject(i);
 JSONObject obj=new JSONObject();
 obj.put("your key","your value");
 newArray.put(obj);
 objmain.put("New array key",newArray);
}