C#使用Newtonsoft.Json将JSON字符串反序列化为对象

问题描述:

我想将一个json字符串转换为使用Newtonsoft.json的对象,但我遇到了下列转换的一些问题。我想知道有人能解释这一点。谢谢。C#使用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对象(例如 { “名称” :“value”})以正确地反序列化

+0

“IdentifyResponse”类的定义在哪里。 –

+0

对不起,我复制了错误的代码行。我打算将字符串转换为AddFaceResponse。我只是更新它。 @TravisJ – EricMA

您正在将数组反序列化为对象。你可以让它工作;

var faces = JsonConvert.DeserializeObject<Face[]>(responseContentStr); 

或者用另一对accolades包装您的JSON字符串,然后添加一个属性;

{"faces":[.. your JSON string ..]} 
+0

对不起,我复制了错误的代码行。我试图将其转换为AddFaceResponse。 – EricMA

+0

它的工作原理,谢谢@Kolky – EricMA