1

字段被忽略。我成功地取回了 2 个对象的列表,但没有填充任何字段。我究竟做错了什么?(不幸的是,我无法控制 json 格式。它完全采用这种结构。

using System.Web.Script.Serialization;

public void myMethod {
  string myContent = @"
  [
    {
        "my_object": {
            "city": "city 1", 
            "myAge": 15
        }
    },
    {
        "my_object": {
            "city": "city 2", 
            "myAge": 18
        }
    }
  ]";

  JavaScriptSerializer serializer = new JavaScriptSerializer();
  List<my_object> list = serializer.Deserialize<List<my_object>>(myContent);

}

public class json_content {
  public string city { get; set; }
  public int myAge { get; set; }
}
4

2 回答 2

2

json_content您的 JSON 中有具有一个属性的对象列表,但期望列表直接包含json_content对象。

最有可能的解决方法是从 JSON 中删除中间对象(如果您控制它):

[
  {
     "city": "city 1", 
     "myAge": 15
  },...
];

如果您不控制 JSON 添加外部类:

class JsonOuterContent
{ 
   public JsonContent json_content;
}

List<JsonOuterContent> list = serializer
      .Deserialize<List<JsonOuterContent>>(myContent);
于 2013-07-25T22:00:10.623 回答
2

此代码解决了您的问题:

public void myMethod()
{
    string myContent = @"
        [
            {
                ""json_content"": {
                    ""city"": ""city 1"", 
                    ""myAge"": 15
                }
            },
            {
                ""json_content"": {
                    ""city"": ""city 2"", 
                    ""myAge"": 18
                }
            }
        ]";

    JavaScriptSerializer serializer = new JavaScriptSerializer();
    List<wrapper> list = serializer.Deserialize<List<wrapper>>(myContent);
}

public class wrapper
{
    public json_content json_content { get; set; }
}

public class json_content
{
    public string city { get; set; }
    public int myAge { get; set; }
}
于 2013-07-25T22:02:47.597 回答