Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
68 views
in Technique[技术] by (71.8m points)

c# - Deserializing JSON into an object

I have some JSON:

{
    "foo" : [ 
        { "bar" : "baz" },
        { "bar" : "qux" }
    ]
}

And I want to deserialize this into a collection. I have defined this class:

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

However, the following code does not work:

 JsonConvert.DeserializeObject<List<Foo>>(jsonString);

How can I deserialize my JSON?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That JSON is not a Foo JSON array. The code JsonConvert.DeserializeObject<T>(jsonString) will parse the JSON string from the root on up, and your type T must match that JSON structure exactly. The parser is not going to guess which JSON member is supposed to represent the List<Foo> you're looking for.

You need a root object, that represents the JSON from the root element.

You can easily let the classes to do that be generated from a sample JSON. To do this, copy your JSON and click Edit -> Paste Special -> Paste JSON As Classes in Visual Studio.

Alternatively, you could do the same on http://json2csharp.com, which generates more or less the same classes.

You'll see that the collection actually is one element deeper than expected:

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

public class RootObject
{
    public List<Foo> foo { get; set; }
}

Now you can deserialize the JSON from the root (and be sure to rename RootObject to something useful):

var rootObject = JsonConvert.DeserializeObject<RootObject>(jsonString);

And access the collection:

foreach (var foo in rootObject.foo)
{
    // foo is a `Foo`

}

You can always rename properties to follow your casing convention and apply a JsonProperty attribute to them:

public class Foo
{
    [JsonProperty("bar")]
    public string Bar { get; set; }
}

Also make sure that the JSON contains enough sample data. The class parser will have to guess the appropriate C# type based on the contents found in the JSON.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...