我试图从Android App读取GET JSON响应,Server是在ASP .net中实现的WCF Web服务
[OperationContract(Name = "Employee")]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedResponse, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, UriTemplate = "person/{name}")]
Person GetPersonData(string name);
以下是浏览器的回复:
{" EmployeeResult" {"年龄":31,"名称":" TESTUSER"}}
{"员工" {"年龄":31,"名称":" TESTUSER"}}
我尝试使用以下代码在Android应用中提取年龄和名称
JSONObject jsonRootObject = new JSONObject(jsonStr); JSONArray jsonArray = jsonRootObject.optJSONArray("EmployeeResult"); for(int i=0; i < jsonArray.length(); i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); int id = Integer.parseInt(jsonObject.optString("Age").toString()); String name = jsonObject.optString("Name").toString(); Log.i("JsonClient", "Age: "+id+" Name: "+name); }
jsonArray是为什么? JSON格式不正确吗? jsonRootObject不为null,jsonStr具有正确的响应文本
由于
答案 0 :(得分:2)
EmployeeResult 不是JsonArray它是JsonObject
将您的json响应粘贴到以下链接
JSONObject jsonRootObject = new JSONObject(jsonStr);
JSONObject EmployeeResultJsonObject = jsonRootObject.getJSONObject("EmployeeResult");
int id = EmployeeResultJsonObject.getInt("age");
String name = EmployeeResultJsonObject.getString("Name");
Log.i("JsonClient", "Age: "+id+" Name: "+name);
答案 1 :(得分:1)
EmployeeResult
不是JSONArray
,而是JSONObject
。
将其更改为
JSONObject jsonRootObject = new JSONObject(jsonStr);
JSONObject employeeResult = jsonObject.getJSONObject("EmployeeResult");
String name = employeeResult.getString("Name");
int age = employeeResult.getInt("Age");