反序列化到JSON匿名类型的列表

反序列化到JSON匿名类型的列表

本文介绍了反序列化到JSON匿名类型的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON如下:

 [{一:B,C:D},{一:E,C:F}, {一个:G,C:H}]

现在我想deserilize到匿名类型为foo

的对象的列表,这

 无功富=新{A =的String.Empty,C =的String.Empty};

在code是:

  ServiceStackJsonSerializer Jserializer =新ServiceStackJsonSerializer();
  动态的foo = Jserializer.Deserialize<名单,LT; foo.GetType()>>(jsonString);

但无法正常工作。

更新:

替换 ServiceStack 的JavaScriptSerializer 并通过词典[] 解决而不需要的问题匿名键入

 的JavaScriptSerializer jSerializer =新的JavaScriptSerializer();
        变种FOOS = jSerializer.Deserialize&所述;词典&下;串,对象> []≥(jsonString);


解决方案

我不知道 Jserializer 类是什么,但我知道的 的JavaScriptSerializer 类。不幸的是,它不支持反序列化到匿名类型。你必须创建一个具体类型是这样的:

 类Foo
{
    公共字符串{搞定;组; }    公共串c {搞定;组; }
}

使用以下code为我工作:

 常量字符串JSON =
    @[{一个:B,C:d的},{,一个,:,e的,C: F},{,一个,:,G,C:H}];VAR FOOS =新的JavaScriptSerializer()反序列化<富[]>(JSON);

变量 FOOS 将包含实例的数组。

I have a json as below :

  "[{"a":"b","c":"d"},{"a":"e","c":"f"},{"a":"g","c":"h"}]"

now I want to deserilize this into a list of objects of anonymous type "foo"

  var foo=new { a=string.empty , c=string.empty };

the code is :

  ServiceStackJsonSerializer Jserializer = new ServiceStackJsonSerializer();
  dynamic foos = Jserializer.Deserialize<List<foo.GetType()>>(jsonString);

but not working .

update :

replacing ServiceStack with JavascriptSerializer and passing dictionary[] solved the problem without need to anonymous Type

        JavaScriptSerializer jSerializer = new JavaScriptSerializer();
        var Foos = jSerializer.Deserialize<Dictionary<string, object>[]>(jsonString);
解决方案

I don't know what the Jserializer class is, but I do know of the JavaScriptSerializer class. Unfortunately, it doesn't support deserialization into anonymous types. You'll have to create a concrete type like this:

class Foo
{
    public string a { get; set; }

    public string c { get; set; }
}

Using the following code worked for me:

const string json =
    @"[{""a"":""b"",""c"":""d""},{""a"":""e"",""c"":""f""},{""a"":""g"",""c"":""h""}]";

var foos = new JavaScriptSerializer().Deserialize<Foo[]>(json);

the variable foos will contain an array of Foo instances.

这篇关于反序列化到JSON匿名类型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:50