2013-02-15 4 views
1

j'ai une variable de type String comme ceci:JSON analyse syntaxique de type variable chaîne

String response_str="[{"Code":"AC_70","Id":1,"Lat":23.847153,"Lon":88.254636,"Name":"Rejinagar"},{"Code":"AC_51","Id":2,"Lat":25.024795,"Lon":88.118248,"Name":"Englishbazar"}] 
"; 

Maintenant, j'ai créé une méthode, comme ceci:

public void parse_json_str(String json_str) 
    { 


     Log.i("String: ",json_str); 


    } 

Je suis passé par le tutoriel here et J'ai une méthode pour le faire.

private void JsonParsing() { 
    JSONObject jObject; 
    String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}"; 
    try { 
    jObject = new JSONObject(jString); 

    JSONObject menuObject = jObject.getJSONObject("menu"); 
    String attributeId = menuObject.getString("id"); 
    System.out.println(attributeId); 

    String attributeValue = menuObject.getString("value"); 
    System.out.println(attributeValue); 

    JSONObject popupObject = menuObject.getJSONObject("popup"); 
    JSONArray menuitemArray = popupObject.getJSONArray("menuitem"); 

    for (int i = 0; i < 3; i++) { 
    Log.i("Value",menuitemArray.getJSONObject(i) 
     .getString("value").toString()); 
    Log.i("Onclick:", menuitemArray.getJSONObject(i).getString(
     "onclick").toString()); 
    } 
    } catch (Exception e) { 
    e.printStackTrace(); 
    } 

} 

Le problème est que, les JSONs sont des structures différentes, je veux analyser mon JSON de la même manière. Mon json ne contient aucun nœud mère. Toutes les suggestions sur la façon d'analyser le json seront d'une grande aide.

Répondre

2

Vous devriez regarder de plus près la structure. Ce JSON est un tableau avec 2 objets. Donc, après avoir créé JSONArray, vous devez parcourir tous les objets JSON possibles.

[ 
    { 
     "Code":"AC_70", 
     "Id":1, 
     "Lat":23.847153, 
     "Lon":88.254636, 
     "Name":"Rejinagar" 
    }, 
    { 
     "Code":"AC_51", 
     "Id":2, 
     "Lat":25.024795, 
     "Lon":88.118248, 
     "Name":"Englishbazar" 
    } 
] 

code:

private void JsonParsing() 
{ 
    JSONArray lJSONArray; 
    String jString = "your JSON here"; 
    try 
    { 
     lJSONArray = new JSONArray(jString); 

     JSONObject lJSONObject; 
     for (int i = 0; i < lJSONArray.length(); i++) 
     { 
      lJSONObject = lJSONArray.getJSONObject(i); 
      // PARSE FIELD HERE 
      String lCode = lJSONObject.getString("Code"); 
      // ETC 

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

} 

essayez avec ce :)