无法从CouchDB反序列化Json

丹尼斯·霍斯特坎普

我正在努力反序列化我得到的Json。

看起来像这样:

{
    "seq": "13-g1AAAACLeJz",
    "id": "c32b670-37899h8c545",
    "changes": [
        {
            "rev": "9-68joc97b73df883a"
        }
    ]
}
{
    "seq": "15-g1AAAACLeJzLYWB-w",
    "id": "f73huvh3-of38j8fh",
    "changes": [
        {
            "rev": "4-10516b0f3"
        }
    ],
    "deleted": true
}
{
    "seq": "16-g1AAAACL4eJzL",
    "id": "M.Mustermann",
    "changes": [
        {
            "rev": "388-e6d350281"
        }
    ],
    "deleted": true
}
{
    "seq": "17-g1AAAACLr43_Q",
    "id": "f8h83hf-34f8h",
    "changes": [
        {
            "rev": "4-773re8f44e"
        }
    ],
    "deleted": true
}
{
    "seq": "18-g1AAwe_g",
    "id": "ewf/34r",
    "changes": [
        {
            "rev": "9-wehch87ewc"
        }
    ],
    "deleted": true
}
{
    "last_seq": "21-g1AA8wd998rAQ",
    "pending": 0
}

我的模特:

public class Root    {
        public List<Result> results { get; set; } 
        public string last_seq { get; set; } 
        public int pending { get; set; } 
    }    

    public class Result
    {
        public string seq { get; set; }
        public string id { get; set; }
        public List<Change> changes { get; set; }
        public bool? deleted { get; set; }
    }

    public class Change
    {
        public string rev { get; set; }
    }

我尝试了所有发现的解决方案,但无济于事,但仍然出现以下异常:

Newtonsoft.Json.JsonReaderException:阅读完JSON内容后遇到的其他文本:{。路径'',第2行,位置0.在Newtonsoft.Json.JsonTextReader.Read()

我试过的

dynamic array = JsonConvert.DeserializeObject<Root>(json);

Root jsonObject = JsonConvert.DeserializeObject<Root>(json);

var jsonObject = JsonConvert.DeserializeObject<List<Root>>(json);

戴维

您所拥有的是一系列都粘在一起的JSON文档。为了使事情更加尴尬,最后一个不同于其他。因此,您需要手动解析所有对象,并进行一些检查以查看所拥有的对象类型。您可以使用该JsonReader.SupportMultipleContent属性。例如,如下所示:

//Somewhere to keep the parsed results
var results = new List<Result>();
Root root = null;

var serializer = new JsonSerializer();

using (var stringReader = new StringReader(Json))
using (var jsonReader = new JsonTextReader(stringReader))
{
    //Make sure the JsonReader knows we have multiple documents
    jsonReader.SupportMultipleContent = true;

    while (jsonReader.Read())
    {
        //Read in the next document
        var nextObject = JObject.ReadFrom(jsonReader);

        //Determine if we are on the last item or not
        if(nextObject["last_seq"] != null)
        {
            root = nextObject.ToObject<Root>();
        }
        else
        {
            results.Add(nextObject.ToObject<Result>());
        }
    }
}

//Store the results in the root object since this is how your classes have been structured
if(root != null)
{
    root.results = results;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章