![](/img/trans.png)
[英]Struggling to deserialize a JSON string using Newtonsoft.JSON in C#
[英]C# Deserialize JSON string into object using Newtonsoft.Json
我正在嘗試使用Newtonsoft.json將json字符串轉換為對象,但是以下轉換存在一些問題。 我不知道有人能解釋這一點。 謝謝。
AddFaceResponse ir = JsonConvert.DeserializeObject<AddFaceResponse>(responseContentStr);
這是json字符串responseContentStr
[{
"faceId": "1fe48282-a3b0-47d1-8fa8-67c4fac3d984",
"faceRectangle": {
"top": 80,
"left": 50,
"width": 147,
"height": 147
}
}]
這是我的模型對象。
public class AddFaceResponse
{
public class Face
{
public class FaceRectangle
{
public int top, left, width, height;
public FaceRectangle(int t, int l, int w, int h)
{
top = t;
left = l;
width = w;
height = h;
}
}
public string faceId;
public FaceRectangle faceRectangle;
public Face(string id, FaceRectangle fac)
{
faceId = id;
faceRectangle = fac;
}
}
Face[] faces;
public AddFaceResponse(Face[] f)
{
faces = f;
}
}
這是我從Visual Studio得到的錯誤。
Newtonsoft.Json.JsonSerializationException:無法將當前JSON數組(例如[1,2,3])反序列化為類型'App2.AddFaceResponse',因為該類型需要JSON對象(例如{“ name”:“ value”})進行反序列化正確地
您正在將數組反序列化為對象。 您可以使用它;
var faces = JsonConvert.DeserializeObject<Face[]>(responseContentStr);
或者將您的JSON字符串換成另一對{},並添加一個屬性;
{"faces":[.. your JSON string ..]}
改善Kolky的答案,您可以將反序列化的數據接收到數組中
Face[] faces = JsonConvert.DeserializeObject<Face[]>(responseContentStr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.