简体   繁体   中英

Collection+JSON deserialization into object

I'm having a problem deserializing Collection+JSON( http://amundsen.com/media-types/collection/format/ ) into an object using C# and asp.net

JSON format: { "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": "" }] }] } }

I have no problems with using (or not using) JSON.net but haven't been able to get it to deserialize properly either way. I have the 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);
}

THE ERROR using JSON.NET: Additional information: Error reading string. Unexpected token: StartObject. Path 'collection', line 1, position 15.

Thanks for your help...

collection is not a string

Your declaration should be as:

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

You may want to visit that site http://json2csharp.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM