繁体   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