Parse Json to String android studio

19,424

You should try this:

String str = "your json string";
JSONObject json = new JSONObject(str);
String module = json.getJSONObject("1").getString("id_module");
String address = json.getJSONObject("1").getString("adresse_mac");
String module2 = json.getJSONObject("2").getString("id_module");  //from 2nd object
Share:
19,424

Related videos on Youtube

cofudayffy
Author by

cofudayffy

Updated on June 04, 2022

Comments

  • cofudayffy
    cofudayffy almost 2 years

    I have this JSON object:

    {
      "1":{
        "id_module":"f83d6101cc",
        "adresse_mac":"00:6A:8E:16:C6:26",
        "mot_de_passe":"mp0001","name":"a"
      },  
      "2":{
        "id_module":"64eae5403b",
        "adresse_mac":"00:6A:8E:16:C6:26",
        "mot_de_passe":"mp0002",
        "name":"a"
      }
    }
    

    And I would like to parse and get to string id_module, adresse_mac, mot_de_passe and name for each thing the 1 and the 2.

    So I made this but it's not working :

    TextView txt1=(TextView) findViewById(R.id.textView);
    String ajout1 = "http://";
    JSONObject json = null;
    String str = "1";
    HttpResponse response;
    HttpClient myClient = new DefaultHttpClient();
    HttpPost myConnection = new HttpPost(ajout1);
    try {
        response = myClient.execute(myConnection);
        str = EntityUtils.toString(response.getEntity(), "UTF-8");
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        JSONObject jsonObject = new JSONObject(str);
        String MAC = jsonObject.getString("id_module");
        txt1.setText(MAC);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    
    • Blackbelt
      Blackbelt about 9 years
      str is a JSONObject, not JSONArray
    • domi
      domi about 9 years
      Make sure you are calling this on non GUI thread (new thread, AsyncTask,...)