集合+JSON反序列化成对象

本文关键字:对象 反序列化 +JSON 集合 | 更新日期: 2023-09-27 18:06:52

我有一个问题反序列化集合+JSON(http://amundsen.com/media-types/collection/format/)成一个对象使用c#和asp.net

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的错误。附加信息:读取字符串错误。意外令牌:starobject。路径'collection',第一行,位置15。

集合+JSON反序列化成对象

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/