JSON响应未映射到android

时间:2015-07-27 18:29:08

标签: android json wcf

我试图从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"}}

  1. 我怎样才能这样做:
  2.   

    {"员工" {"年龄":31,"名称":" TESTUSER"}}

    1. 我尝试使用以下代码在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);
       }
      
    2. jsonArray是为什么? JSON格式不正确吗? jsonRootObject不为null,jsonStr具有正确的响应文本

      由于

2 个答案:

答案 0 :(得分:2)

EmployeeResult 不是JsonArray它是JsonObject

将您的json响应粘贴到以下链接

http://json.parser.online.fr/

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");