使用Javascriptserializer反序列化为自定义类型

时间:2015-10-22 06:51:00

标签: c# json deserialization

我使用JavaScriptSerializer将json反序列化为我制作的类但我遇到了问题。

我试图序列化的json就是这种形式。 json的形式不在我的掌控之中。

      {"list": {
        "p1": {
          "a": 6,
          "b": 7
        },
        "p2": {
          "a": 1,
          "b": 1
        }
       }

我试图将其反序列化为这样的类;

public class jsonObject 
{
    public listType list {get;set;}

    internal class listType 
    { 

    }

}

和我的反序列化方法;

var engine = new JavaScriptSerializer();
dynamic foo = engine.Deserialize<jsonObject>(json);

我无法弄清楚如何处理列表中的项目。它不是一个数组,它内部的对象数量可能会有所不同。它有时只是p1,它有时会持续到p7。除了在listType中声明p1,p2,p3,p4,p5,p6,p7之外,还有解决方法吗?

4 个答案:

答案 0 :(得分:1)

您的JSON字符串似乎不正确。 试着用这个:

{"list": [
    "p1": {
      "a": 6,
      "b": 7
    },
    "p2": {
      "a": 1,
      "b": 1
    }]
}

我已为列表添加了一个左括号,以便将其标记为对象,并将数组左括号更改为方括号。

答案 1 :(得分:0)

试试这个

var foo = engine.Deserialize<List<jsonObject>>(json);

答案 2 :(得分:0)

好的,我发现了一些有用的东西;

我已经创建了另一个类,我们称之为childType

public childType
{
   public int a {get;set;}
   public int b {get;set;}
}

然后我将listType声明为

 public Dictionary<string,childType> list {get;set;}

字典的键被证明是json(p1,p2,p3,p4)中子对象的名称,并且值已分配给childType。

答案 3 :(得分:0)

您获得的json格式必须正确转义。他们可以像这样使用Json.Net来解析它。

JObject obj = JObject.Parse(@"
     {""list"": {
        ""p1"": {
          ""a"": 6,
          ""b"": 7
        },
        ""p2"": {
          ""a"": 1,
          ""b"": 1
        }
       }}
    ");

您说您不确定list内的属性名称是什么。因此,我将使用Children()

JProperty方法
//In case you are not sure if `a` or `b` will also change their name go for this using an anonymous type

        var result =    obj.Property("list")
    .Children()
    .Children()
    .Children()
    .Select(x=> new {a =x.Children().ElementAt(0).ToString(), b = x.Children().ElementAt(1).ToString()});

//In case you are sure about `a` and `b` go for this using an anonymous type

        var result =    obj.Property("list")
    .Children()
    .Children()
    .Children()
    .Select(x=> new {a =x["a"].ToString(), b = x["b"].ToString()});

//In case you need a concrete type to store your data,i am using your class `childType`

        public class childType
        {
           public int a {get;set;}
           public int b {get;set;}
        }

            List<childType> lst = obj.Property("list")
    .Children()
    .Children()
    .Children()
    .Select(x=> new childType {a =Convert.ToInt32(x["a"]), b = Convert.ToInt32(x["b"])}).ToList();

我想出了JObject知识有限的解决方案。它需要改进。

相关问题