2017-01-04 161 views
-3

有人可以给我一个很好的链接或有助于解释解析JSON的工作。我有一个像这样的对象数组........ [{} {} {}]。我试图得到例如{“名称”的价值:“约翰”....}我是否调用.get(name)来获取值John.or .getString(name)来获得值约翰。我试图调用getstring(ETA),并且有一个事件发生在另一个对象上[{“name”:“John”,“Eta”:“5”} ....]错误不能在对象上使用.getstring(Eta)。这可能与某些json有类似/“Time”的事实有关:JSON.stringify() - 将JavaScript对象转换为JSON字符串。“(0004253200)”/解析JSON数组和对象

回答

0

我会尝试解释如何在Android中使用JSON。

假设你有一个像

{ 
    "contacts": [ 
     { 
       "id": "c200", 
       "name": "Ravi Tamada", 
       "email": "[email protected]", 
       "address": "xx-xx-xxxx,x - street, x - country", 
       "gender" : "male", 
       "phone": { 
        "mobile": "+91 0000000000", 
        "home": "00 000000", 
        "office": "00 000000" 
       } 
     }, 
     { 
       "id": "c201", 
       "name": "Johnny Depp", 
       "email": "[email protected]", 
       "address": "xx-xx-xxxx,x - street, x - country", 
       "gender" : "male", 
       "phone": { 
        "mobile": "+91 0000000000", 
        "home": "00 000000", 
        "office": "00 000000" 
       } 
     } 
    ] 
} 

字符串现在{}之间的任何一个JSON对象。所以这整个字符串可以转换为一个JSON对象。

要做到这一点:JSONObject obj = new JSONObject(str);

和任何[]之间是一个JSON阵列。在上面的例子中,"contacts"是一个JSONArray。

为了得到阵列JSONArray contacts = jsonObj.getJSONArray("contacts");

现在,假设你需要得到接触式ID C201的名称的值。

JSONObject obj = new JSONObject(str); //Convert whole string to JSONObject. 
JSONArray contacts = jsonObj.getJSONArray("contacts"); //Get contacts array. 
// looping through All Contacts 
for (int i = 0; i < contacts.length(); i++) { 
    JSONObject c = contacts.getJSONObject(i); //Get JSONObject at index i 
    if(c.getString("id").equals("c201")){ 
     return c.getString("name"); 
    } 
} 

看看this article更多的阅读材料。

+0

谢谢你的回答和链接我能得到一个更好的理解之间。 – Vahalaru

0

JSON.stringify

JSON.parse()来 - 转换JSON字符串成javascript对象。

0
String json = "{"name" :"John"}"; 
JsonObject object = new JsonObiect(json); 
String name = object.getString("name"); 
System.out.println(name);