【问题标题】:Cannot deserialize Json to object无法将 Json 反序列化为对象
【发布时间】:2014-03-19 15:56:01
【问题描述】:

这是我的 Json:

{"Username":"Test","ProductIds":"[30, 50]","RouteName":"ABCD"}

这是我的对象:

public class SuggestMobileModel
    {
        public string Username { get; set; }
        public List<int> ProductIds { get; set; }
        public string RouteName { get; set; }
    }

当我将该 Json 转换为该对象时,我可以收到 UsernameRouteName,但 ProductIds 始终为空。它仅在我删除 ProductIds 值中的引号时才有效,如下所示:

{"Username":"Test","ProductIds":[30, 50],"RouteName":"ABCD"}

我现在可以做些什么来成功反序列化而不删除代码?那个 Json 是由代码生成的,所以它总是有那个引号。

---编辑!!!---

这是创建该 Json 字符串的 Java 代码。它有什么错误吗?它正在使用org.json 库。

// 1. create HttpClient
            HttpClient client = new DefaultHttpClient();
            HttpResponse response;

            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(urlSuggestRoute);

            String json = "";

            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("Username", User.getUsername());
            List<Integer> listProductIds = new ArrayList<Integer>();
            if (Cart.getCart() != null && Cart.getSize() > 0) {
                for (int i = 0; i < Cart.getSize(); i++) {
                    listProductIds.add(Cart.getCartItem(i)
                            .getProductAttribute().getProductId());
                }
            }
            jsonObject.accumulate("ProductIds", listProductIds);
            jsonObject.accumulate("RouteName", txtRoute.getSelectedItem()
                    .toString());

            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();

            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);

            // 6. set httpPost Entity
            httpPost.setEntity(se);

            // 7. Set some headers to inform server about the type of the
            // content
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = client.execute(httpPost);

【问题讨论】:

  • 您使用的是哪个 JSON 库?
  • 目前,我将此 Json 发送到 Web API 控制器并让它自行反序列化。我也尝试过使用 Newtonsoft,但没有帮助。
  • 谢谢,不过没关系,只需检查 JSON 规范即可。请参阅下面的答案。
  • 您确实应该修复生成无效 JSON 并将数组用双引号括起来的代码。该值是字符串的有效 JSON,而不是值数组。
  • 我已经添加了创建该 Json 字符串的代码。请看一下。非常感谢您的帮助。

标签: c# json deserialization json-deserialization


【解决方案1】:

在数组值周围加上双引号是无效的 JSON(请参阅http://json.org/ 的语言语法)。因此,您的 JSON 解析器可能不支持。

附加背景信息:您的 JSON 将 ProductIds 定义为字符串值 [30, 50] 的对。

【讨论】:

  • 那么将其定义为整数数组的正确方法是什么?
  • 和你一样,但是,没有双引号,即:...,"ProductIds":[30, 50],...
【解决方案2】:

好的,我想通了。在生成 Json 的代码中,我应该使用 JsonArray 而不是 List&lt;Integer&gt;,然后库不会在数组周围加上引号。

非常感谢您的帮助:)

【讨论】:

    猜你喜欢
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-05
    • 2016-12-30
    • 2014-08-04
    • 1970-01-01
    相关资源
    最近更新 更多