簡體   English   中英

將Json解析為String android studio

[英]Parse Json to String android studio

我有這個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"
  }
}

我想解析並獲得字符串id_moduleadresse_macmot_de_passe以及1和2中每個事物的name

所以我做了這個,但它不起作用:

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

你應該試試這個:

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

我推薦使用谷歌的gson。

看看這個教程

GSON讓現場更方便!

您也可以查看傑克遜的表現獎金。

教程: JackSon在5分鍾內完成

或谷歌的Gson有點更優雅的api。

嘗試這個:

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"}}

然后:

JSONObject obj = new JSONObject(json);

希望它會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM