C# serialize JSON without property name

半城伤御伤魂 提交于 2020-02-06 11:22:48

问题


maybe this was asked somewhere before, but I don't know how to search for my problem. I'm using a WebAPI to verify licenses. From this API I get the return JSON string in follwing format.

string json = "[{"status":"error","status_code":"e002","message":"Invalid licence key"}]"

This is my serializer

using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
                DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(ActivationResponseWooSl));
                ActivationResponseWooSl ar = (ActivationResponseWooSl)js.ReadObject(ms);
}

Now my questions is, how must the "ActivationResponseWooSl" class look like so that the serializer can convert it?

Any help is highly appreciated!

For now it looks like that (what's not workiing):

[DataContract]
public class ActivationResponseWooSl
{
    [DataMember(Name = "status")]
    public string Status { get; set; }

    [DataMember(Name = "status_code")]
    public string ErrorCode { get; set; }

    [DataMember(Name = "message")]
    public string ErrorMessage { get; set; }
}

However when I serialize my json string, all properties are "null".


回答1:


Your class is correct. Your JSON is an array of object.

Try

DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(ActivationResponseWooSl[]));
var arr = (ActivationResponseWooSl[])js.ReadObject(ms);


来源:https://stackoverflow.com/questions/53228506/c-sharp-serialize-json-without-property-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!