[英]Parsing Json in Java trouble with json format android
How can I get the information from my .json file with the following format?:如何从我的 .json 文件中获取以下格式的信息?:
[{"name":"My name","country":"Country name"}]
I'm getting with the following:我得到以下内容:
Json file: json文件:
{"name":"My name","country":"Country name"}
Java file: Java文件:
@Override
protected JSONObject doInBackground(String... args) {
JsonParser jParser = new JsonParser();
JSONObject json;
json = jParser.getJSONFromUrl("http://example.com/myfile.json");
System.out.println("JSON: " + json);
if(json != null) {
try {
name = json.getString("name");
country = json.getString("country");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
You are not getting JSONObject
in your response, you are getting JSONArray
that holds one object.您没有在响应中获得
JSONObject
,而是获得了包含一个对象的JSONArray
。 Therefore these lines are wrong因此这些行是错误的
JSONObject json;
json = jParser.getJSONFromUrl("http://example.com/myfile.json");
And you should replace it with你应该用
JSONArray json;
Then you get your 0th object然后你得到你的第 0 个对象
JSONObject wholeObject = json.getJSONObject(0);
And get strings from it并从中获取字符串
name = wholeObject.getString("name");
country = wholeObject.getString("country");
Can you try this:你能试试这个吗:
protected JSONObject doInBackground(String... args) {
JsonParser jParser = new JsonParser();
JSONObject json;
json = jParser.getJSONFromUrl("http://example.com/myfile.json");
System.out.println("JSON: " + json);
if(json != null) {
try {
JSONArray jsonArray = new JSONArray(json.toString());
JSONObject newJSON = jsonArray.get(0); //first index
name = newJSON.getString("name");
country = newJSON.getString("country");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.