2012-04-30 50 views
2

我想将JSON转换为java代码。我的jsoncode如下所示。如何编写json的java代码

{ 
"nodes": [ 
    { 
     "node": { 
      "Name": "rahul Patel", 
      "Address": "\n\tAhmedabad", 
      "Date of Birth": "1991-05-03", 
      "Occupation": "developer", 
      "Member Since": "3 weeks 4 days" 
     } 
    } 
] 

Java代码

try { 
      JSONObject objResponse = new JSONObject(strResponse); 

      JSONArray jsonnodes = objResponse 
        .getJSONArray(nodes); 


      System.out.println("=hello this is DoinBackground"); 
      for (i = 0; i < jsonnodes.length(); i++) { 

       System.out.println("hello this is for loop of DoinBackground"); 
       JSONObject jsonnode = jsonnodes.getJSONObject(i); 

       JSONObject jsonnodevalue = jsonnode 
         .getJSONObject(node); 

       bean = new UserProfileBean(); 

       bean.name = jsonnodevalue.getString(Name); 


       listActivities.add(bean); 

      } 
     } catch (JSONException e) { 

      e.printStackTrace(); 
     } 
} 

在这里,我logcat中打印的价值之前,循环System.out.println("=hello this is DoinBackground");,但值不能在打印的for循环System.out.println("hello this is for loop of DoinBackground");

注:请让我知道,是否有可能我们不能在代码中使用循环?如果是,那么给出解决方案,对于这个给定的问题还有另一种解决方案。

谢谢。

回答

1

你的json字符串是错误的。它必须与}一起发布。解决这个问题,它会工作。

固定JSON字符串:

{ 
    "nodes": [ 
     { 
      "node": { 
       "Name": "rahul Patel", 
       "Address": "\n\tAhmedabad", 
       "Date of Birth": "1991-05-03", 
       "Occupation": "developer", 
       "Member Since": "3 weeks 4 days" 
      } 
     } 
    ] 
} 

示例代码进行测试:

String j = "{\r\n" + 
     " \"nodes\": [\r\n" + 
     "  {\r\n" + 
     "   \"node\": {\r\n" + 
     "    \"Name\": \"rahul Patel\",\r\n" + 
     "    \"Address\": \"\\n\\tAhmedabad\",\r\n" + 
     "    \"Date of Birth\": \"1991-05-03\",\r\n" + 
     "    \"Occupation\": \"developer\",\r\n" + 
     "    \"Member Since\": \"3 weeks 4 days\"\r\n" + 
     "   }\r\n" + 
     "  }\r\n" + 
     " ]\r\n" + 
     "}"; 

try{ 
    JSONObject objResponse = new JSONObject(j); 

    JSONArray jsonnodes = objResponse.getJSONArray("nodes"); 

    for (int i = 0; i < jsonnodes.length(); i++) { 

     JSONObject jsonnode = jsonnodes.getJSONObject(i); 

     JSONObject jsonnodevalue = jsonnode 
       .getJSONObject("node"); 

     Log.v("name", jsonnodevalue.getString("Name")); 
     Log.v("address", jsonnodevalue.getString("Address")); 
     Log.v("occupation", jsonnodevalue.getString("Occupation")); 
    } 

} 
catch (Exception e) { 
    e.printStackTrace(); 
} 
+0

谢谢, 没有for循环可能吗? –

+0

其可能但不推荐,因为数组总是更好地通过循环访问。但是,您可以使用'while'循环代替'for循环,但我认为它不会对您的情况产生任何影响。但是如果你知道你总是会得到一个数组中的一个对象,那么你可以通过简单地使用索引值来跳过数组。 'JSONObject jsonnode = jsonnodes.getJSONObject(0);' – waqaslam

+0

@RahulPatel它可能,但如果我们是json中的多个元素,那么这个for循环将被使用。和单个项目,我们可以做到这一点没有循环 – user1089679

1

尝试使用Gson - http://code.google.com/p/google-gson/。会节省很多头痛。

但是,在您的代码中,请确保您的JSON字符串正在被正确解析。 可以肯定的objResponse.getJSONArray(nodes)应该是objResponse.getJSONArray("nodes")

+0

谢谢, 请让我知道在logcat中为什么它不适合循环后显示。 –