【问题标题】:JSON response not mapped to JSONObject in androidJSON响应未映射到android中的JSONObject
【发布时间】:2015-07-27 18:29:07
【问题描述】:

我正在尝试从 android App 读取 GET JSON 响应,服务器是在 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":{"Age":31,"Name":"testuser"}}

  1. 我怎样才能做到这一点:

{"Employee":{"Age":31,"Name":"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);
     }
    

jsonArray 为空,为什么? JSON格式不正确吗? jsonRootObject 不为空且 jsonStr 具有正确的响应文本

谢谢

【问题讨论】:

  • 请查看 json 语法:w3schools.com/json/json_syntax.asp
  • JSON 对象写在花括号内。和 JSON 数组写在方括号内。如何为 JSON 数组生成方括号以及如何从响应中删除“结果”字符串?

标签: android json wcf


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    EmployeeResult 不是JSONArray,而是JSONObject

    改成

    JSONObject  jsonRootObject = new JSONObject(jsonStr);
    JSONObject employeeResult = jsonObject.getJSONObject("EmployeeResult");
    String name = employeeResult.getString("Name");
    int age = employeeResult.getInt("Age");
    

    【讨论】:

    • 解法正确,改语法即可
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 2020-09-13
    • 2023-03-10
    • 2014-04-12
    • 2020-02-05
    • 1970-01-01
    • 2018-02-06
    相关资源
    最近更新 更多