【问题标题】:C# serialize JSON without property nameC#序列化没有属性名的JSON
【发布时间】:2018-11-09 15:20:24
【问题描述】:

也许以前有人问过这个问题,但我不知道如何搜索我的问题。 我正在使用 WebAPI 来验证许可证。从这个 API 我得到以下格式的返回 JSON 字符串。

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

这是我的序列化器

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

现在我的问题是,“ActivationResponseWooSl”类必须是什么样子才能让序列化程序转换它?

非常感谢任何帮助!

现在看起来像这样(什么不起作用):

[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; }
}

但是,当我序列化我的 json 字符串时,所有属性都是“null”。

【问题讨论】:

    标签: c# json serialization


    【解决方案1】:

    你的课是正确的。您的 JSON 是一个对象数组。

    试试

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

    【讨论】:

    • 这是快速且完美的解决方案!非常感谢您的快速支持:)
    • @AndreasReitberger 很高兴为您提供帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多