java 将 Json 解析为 String android studio
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28302812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parse Json to String android studio
提问by cofudayffy
I have this JSON object:
我有这个 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"
}
}
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.
我想解析并获取 string id_module
, adresse_mac
,mot_de_passe
以及name
1 和 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();
}
回答by Shaishav Jogani
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
回答by damson
You may also check Hymansonfor a performance bonus.
您也可以查看Hymanson的绩效奖金。
Tutorial: HymanSon in 5 minutes
教程:Hyman逊 5 分钟
or Gsonby Google for a kinda more elegant api.
或Google 的Gson以获得更优雅的 api。
回答by tim687
回答by Daniel Krzyczkowski
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.
希望它会有所帮助。