【问题标题】:Collection+JSON deserialization into objectCollection+JSON反序列化成对象
【发布时间】:2014-06-05 19:53:52
【问题描述】:

我在使用 C# 和 asp.net 将 Collection+JSON(http://amundsen.com/media-types/collection/format/) 反序列化为对象时遇到问题

JSON 格式: { "collection": { "version": "1.0", "href": "http://www.example.com/api/", "links": [{ "href": "http://example.com/api/issues", "rel": "issuesLink", "name": "issuesLink", "render": "link", "prompt": "All issues ordered by number" }], "queries": [{ "href": "https:\/\/example.com\/api\/search\/{field}\/{value}", "rel": "searchByField", "name": "FieldSearch", "prompt": "Search by field", "data": [{ "name": "name", "value": "field" }, { "name": "value", "value": "" }] }] } }

我在使用(或不使用)JSON.net 方面没有任何问题,但无论哪种方式都无法让它正确反序列化。我有 JSON

public class FPResponse
{
    [JsonProperty("collection")]
    //I have tried using List<string> too
    // public Billboard collection executes the code but returns null for o
    public string collection { get; set; }
}

public class Billboard
{
    [JsonProperty("version")]
    public string version { get; set; }

    [JsonProperty("href")]
    public string href { get; set; }

    [JsonProperty("links")]
    public IList<LinkSet> links { get; set; }
}

using (var reader = new StreamReader(dataStream))
{
    string rtn = reader.ReadToEnd(); //has the JSON string
    var o = JsonConvert.DeserializeObject<FPResponse>(rtn);
}

使用 JSON.NET 的错误:附加信息:读取字符串时出错。意外标记:StartObject。路径“集合”,第 1 行,位置 15。

感谢您的帮助...

【问题讨论】:

    标签: c# asp.net json json.net


    【解决方案1】:

    collection 不是string

    你的声明应该是:

    public class Link
    {
        public string href { get; set; }
        public string rel { get; set; }
        public string name { get; set; }
        public string render { get; set; }
        public string prompt { get; set; }
    }
    
    public class Datum
    {
        public string name { get; set; }
        public string value { get; set; }
    }
    
    public class Query
    {
        public string href { get; set; }
        public string rel { get; set; }
        public string name { get; set; }
        public string prompt { get; set; }
        public List<Datum> data { get; set; }
    }
    
    public class Collection
    {
        public string version { get; set; }
        public string href { get; set; }
        public List<Link> links { get; set; }
        public List<Query> queries { get; set; }
    }
    
    public class FPResponse
    {
        public Collection collection { get; set; }
    }
    

    您可能想访问该网站http://json2csharp.com/

    【讨论】:

    • 谢谢@L.B 我会在允许时将其标记为已回答。我以前试过这个,但没有设置每个属性。我敢打赌我需要一切才能正确解析。无论如何,您的解决方案就像一个魅力。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    相关资源
    最近更新 更多