【发布时间】: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 转换为该对象时,我可以收到 Username、RouteName,但 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