我正在尝试解析URL以获取JSON响应和该响应中的特定值。我没有示例代码。请给我一个简单的解决方案。 下面我发布了我的网址和回复。我想获得“学校”,“名称”和结果值。
http://sample.com/login/username/ <username> /password <password>?
{
"response":{
"School":"SBOA",
"Name":"Anitha",
"Class":"Tenth",
},
"Result":"Good",
}
我的代码:
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView output = (TextView) findViewById(R.id.textView1);
String strJson="URL";
String data = "";
System.out.println(strJson);
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("response");
System.out.println(jsonRootObject);
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
// int id = Integer.parseInt(jsonObject.optString("id").toString());
String name = jsonObject.optString("School").toString();
// float salary = Float.parseFloat(jsonObject.optString("salary").toString());
// data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";*/
}
//output.setText(data);
} catch (JSONException e) {e.printStackTrace();}
}
}
答案 0 :(得分:0)
如果你有一个名为json的JSONObject,那么按照这个来获取学校价值
try{
jsonRootObject .getJSONObject("response").getString("School");
}catch(JSONException e)
{
e.printStackTrace();
}
答案 1 :(得分:0)
要准确读取JSON,请使用:
/** Verify that your strJson string contains this:
* {
* "response":{
* "School":"SBOA",
* "Name":"Anitha",
* "Class":"Tenth",
* },
* "Result":"Good",
* }
*/
String strJson = ??;
Log.d("TAG", "strJson: " + strJson);
try {
JSONObject jsonRootObject = new JSONObject(strJson);
JSONObject response = jsonRootObject.getJsonObject("response");
String schoolString = response.getString("School");
String nameString = response.getString("Name");
String classString = response.getString("Class");
String result = jsonRootObject.getString("Result");
} catch(JSONException e) {
Log.e("TAG", "Error reading json: " + jsonRootObject.toString());
}