2013-11-02 16 views
10

Mam mały problem z analizą json w mojej aplikacji na Androida.Android parsować JSONObject

To jest jak mój plik JSON wygląda następująco:

{ 
"internalName": "jerry91", 
"dataVersion": 0, 
"name": "Domin91", 
"profileIconId": 578, 
"revisionId": 0, 
} 

Jak widać ta konstrukcja jest trochę dziwne. Nie wiem, jak odczytać te dane w mojej aplikacji. Jak zauważyłem, wszystkie te obiekty nie są tablicami:/

+0

wyjaśnij więcej –

Odpowiedz

2

Ta część zrobić w onBackground w AsyncTask

JSONParser jParser = new JSONParser(); 
JSONObject json = jParser.getJSONFromUrl(url); 


     try { 

      result = json.getString("internalName"); 
          data=json.getString("dataVersion"); 
         ect.. 


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

JsonParser

public class JSONParser { 

static InputStream is = null; 
static JSONObject jObj = null; 
static String json = ""; 

// constructor 
public JSONParser() { 

} 

public JSONObject getJSONFromUrl(String url) { 

    // Making HTTP request 
    try { 
     // defaultHttpClient 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 
     HttpResponse httpResponse = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent(); 

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "utf-8"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     json = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    // try parse the string to a JSON object 
    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    // return JSON String 
    return jObj; 

} 
    } 
21

zawsze można użyć starego dobrego json.org lib. W twoim kodzie Java:

  • Najpierw przeczytaj zawartość pliku json w String;
  • następnie zanalizować go do JSONObject:

    JSONObject myJson = new JSONObject(myJsonString); 
    // use myJson as needed, for example 
    String name = myJson.optString("name"); 
    int profileIconId = myJson.optInt("profileIconId"); 
    // etc 
    
0

Proponuję użyć biblioteki jak gson jak @jmeier napisał na jego odpowiedź.Ale jeśli chcesz obsługiwać json z domyślnych Android, możesz użyć czegoś takiego:

public class MainActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     String s = new String("{\"internalName\": \"domin91\",\"dataVersion\": 0,\"name\": \"Domin91\",\"profileIconId\": 578,\"revisionId\": 0,}"); 

     try { 
      MyObject myObject = new MyObject(s); 
      Log.d("MY_LOG", myObject.toString()); 
     } catch (JSONException e) {   
      Log.d("MY_LOG", "ERROR:" + e.getMessage()); 
     } 


    } 

    private static class MyObject { 
     private String internalName; 
     private int dataVersion; 
     private String name; 
     private int profileIconId; 
     private int revisionId; 

     public MyObject(String jsonAsString) throws JSONException { 
      this(new JSONObject(jsonAsString)); 
     } 

     public MyObject(JSONObject jsonObject) throws JSONException { 
      this.internalName = (String) jsonObject.get("internalName"); 
      this.dataVersion = (Integer) jsonObject.get("dataVersion"); 
      this.name = (String) jsonObject.get("name"); 
      this.profileIconId = (Integer) jsonObject.get("profileIconId"); 
      this.revisionId = (Integer) jsonObject.get("revisionId"); 
     } 

     @Override 
     public String toString() { 
      return "internalName=" + internalName + 
        "dataVersion=" + dataVersion + 
        "name=" + name + 
        "profileIconId=" + profileIconId + 
        "revisionId=" + revisionId; 
     } 

    } 

} 
8

wiedzieć, czy ciąg jest JSONArray lub JSONObject

JSONArray String jest jak ten

[{ 
"internalName": "blaaa", 
"dataVersion": 0, 
"name": "Domin91", 
"profileIconId": 578, 
"revisionId": 0, 
}, 
{ 
"internalName": "blooo", 
"dataVersion": 0, 
"name": "Domin91", 
"profileIconId": 578, 
"revisionId": 0, 
}] 

i ten ciąg jako JSONOject ale jak wywołać elementy z JSONArray i JSONObject?

JSNOObject informacji nazywa się ten

pierwszego napełnienia obiektu z danymi

JSONObject object = new JSONObject(
"{ 
\"internalName\": \"domin91\", 
\"dataVersion\": 0, 
\"name\": \"Domin91\", 
\"profileIconId\": 578, 
\"revisionId\": 0, 
}" 
); 

pozwala teraz informacje o połączeniach z obiektu

String myusername = object.getString("internalName"); 
int dataVersion = object.getInt("dataVersion"); 

Jeśli chcesz wywołać informacje z JSONArray trzeba wiedzieć, co jest numerem pozycji obiektu lub musisz zapętlić JSONArray, aby uzyskać informacje na przykład

pętli tablicę

for (int i = 0; i < jsonarray.length() ; i++) 
{ 
    //this object inside array you can do whatever you want 
    JSONObject object = jsonarray.getJSONObject(i); 
} 

jeśli wiem położenie obiektu wewnątrz JSONArray złego nazwać jak ten

//0 mean first object inside array 
JSONObject object = jsonarray.getJSONObject(0);