简体   繁体   中英

Parse Json to String android studio

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();
}

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

I recommend using gson from Google.

Check out this tutorial

GSON Makes live way more handable!

You may also check Jackson for a performance bonus.

Tutorial: JackSon in 5 minutes

or Gson by Google for a kinda more elegant api.

Try this:

String json = {"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"}}

Then:

JSONObject obj = new JSONObject(json);

Hope it will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM