Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Deserializing a simple JSON array with DataContractJsonSerializer

I'm sure this question has been asked over and over again, but for some reason, I still can't manage to get this to work.

I want to deserialize a JSON object that contains a single member; a string array:

{"results" : ["a", "b"]}

This is the class that I'm trying to deserialize into:

public class Whatever {
    [DataMember(Name = "results")]
    public string[] Results { get; protected set; }
}

And this is the Deserialize method:

private static T Deserialize<T>(string json)
{
    var instance = Activator.CreateInstance<T>();
    using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
    {
        var serializer = new DataContractJsonSerializer(instance.GetType());
        return (T)serializer.ReadObject(ms);
    }
}

A call like Deserialize<Whatever>("{"results" : ["a", "b"]}") is returning an initialized instance of Whatever but the Results array is staying null.

Is there something wrong with the structure of Whatever?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Ah, after posting this I realized that I was missing the DataContract attribute decoration on Whatever:

[DataContract]
public class Whatever {
    [DataMember(Name = "results")]
    public string[] Results { get; protected set; }
}

Now it works fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...