我想在C#(MAUI)中反序列化来自RestResponse
的响应。
request.AddBody(body);
RestResponse response = await client.PostAsync(request);
if (response.IsSuccessful)
{
var list1 = Newtonsoft.Json.JsonConvert.DeserializeObject<List<object>>(response.Content);
}
这里,在if
块中,我想要的响应在一个对象列表中,但是这一行没有执行,我的意思是它从来没有到达if
块的结束语句。怎么办?有这么多的答案,但是我尝试了这么多,对我不起作用。所有人都说这样做:
Newtonsoft.Json.JsonConvert.DeserializeObject<List<object>>(response.Content)
我最初把我的类名List<MyClassName>
,然后想反序列化器如何知道成员,所以用just object替换了它。
请看下面的回答:
"{\"documents\":[{\"_id\":{\"$oid\":\"639f5cb70d319f7bb78a6e0d\"},\"Role\":{\"$numberInt\":\"2\"},\"UserId\":{\"$numberInt\":\"2\"},\"Email\":\"abc\",\"Pass\":\"dgdfgdfh\"},{\"_id\":{\"$oid\":\"639f5d3a0d319f7bb78a6e0e\"},\"Role\":{\"$numberInt\":\"2\"},\"UserId\":{\"$numberInt\":\"3\"},\"Email\":\"abcd\",\"Pass\":\"dgdgdfh\"},{\"_id\":{\"$oid\":\"639f5d900d319f7bb78a6e10\"},\"Role\":{\"$numberInt\":\"2\"},\"UserId\":{\"$numberInt\":\"4\"},\"Email\":\"abcde\",\"Pass\":\"dfgdfhdfhh\"},{\"_id\":{\"$oid\":\"639f5db80d319f7bb78a6e11\"},\"Role\":{\"$numberInt\":\"2\"},\"UserId\":{\"$numberInt\":\"5\"},\"Email\":\"abcdef\",\"Pass\":\"dfhjlfdkjh\"},{\"_id\":{\"$oid\":\"639f5e170d319f7bb78a6e13\"},\"Role\":{\"$numberInt\":\"0\"},\"UserId\":{\"$numberInt\":\"1\"},\"Email\":\"fhdfhg\",\"Pass\":\"ch\"},{\"_id\":{\"$oid\":\"639f79a373de576753175098\"},\"Email\":\"admin\"},{\"_id\":{\"$oid\":\"63a027f853fa7d5e3456d224\"},\"Role\":{\"$numberInt\":\"2\"},\"Email\":\"abc@gmail.com\",\"Pass\":\"12gfgh3a\"}]}"
或者你可以看看这个(同样的):
{
"documents":
[
{
"_id":
{
"$oid": "639f5cb70d319f7bb78a6e0d"
},
"Role":
{
"$numberInt": "2"
},
"UserId":
{
"$numberInt": "2"
},
"Email": "abc",
"Pass": "fhddfh"
},
{
"_id":
{
"$oid": "639f5d3a0d319f7bb78a6e0e"
},
"Role":
{
"$numberInt": "2"
},
"UserId":
{
"$numberInt": "3"
},
"Email": "abcd",
"Pass": "dfhfdh"
},
{
"_id":
{
"$oid": "639f5d900d319f7bb78a6e10"
},
"Role":
{
"$numberInt": "2"
},
"UserId":
{
"$numberInt": "4"
},
"Email": "shiva",
"Pass": "fgsdgsdg"
},
{
"_id":
{
"$oid": "639f5db80d319f7bb78a6e11"
},
"Role":
{
"$numberInt": "2"
},
"UserId":
{
"$numberInt": "5"
},
"Email": "abcdef",
"Pass": "dfgsdfgsdg"
},
{
"_id":
{
"$oid": "639f5e170d319f7bb78a6e13"
},
"Role":
{
"$numberInt": "0"
},
"UserId":
{
"$numberInt": "1"
},
"Email": "abcdefg",
"Pass": "dgsdgch"
},
{
"_id":
{
"$oid": "639f79a373de576753175098"
},
"Email": "admin"
},
{
"_id":
{
"$oid": "63a027f853fa7d5e3456d224"
},
"Role":
{
"$numberInt": "2"
},
"Email": "abc@gmail.com",
"Pass": "12gfgh3a"
}
]
}
谢谢。
2条答案
按热度按时间fnx2tebb1#
您的JSON内容是一个包含
documents
属性(数组类型)的对象。您应该将
response.Content
反序列化为根对象,并提取documents
数组。备选方案:定义
Root
类并反序列化为Root
对象。x一个一个一个一个x一个一个二个x
所附JSON中的 * 语法 * 是MongoDB BsonDocument。我建议使用 * MongoDB. Bson * 库来反序列化响应。
一个三个三个一个
Demo @ .NET Fiddle
zour9fqk2#
从你的json输入,你可以有一个各自的模型类。使用任何在线工具转换成
c# class model
对象,我已经使用了https://json2csharp.com/,下面是类模型输出,然后反序列化对象