【问题标题】:C# Deserialize JSON string into object using Newtonsoft.JsonC# 使用 Newtonsoft.Json 将 JSON 字符串反序列化为对象
【发布时间】:2017-08-14 20:19:25
【问题描述】:

我正在尝试使用 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"}) 正确反序列化

【问题讨论】:

  • IdentifyResponse类的定义在哪里。
  • 抱歉,我复制了错误的代码行。我打算将字符串转换为 AddFaceResponse。我只是更新它。 @TravisJ

标签: c# json serialization json.net


【解决方案1】:

您正在将一个数组反序列化为一个对象。您可以使用它;

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

或者用另一对 accolades { } 包装你的 JSON 字符串,并添加一个属性;

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

【讨论】:

  • 对不起,我复制了错误的代码行。我正在尝试将其转换为 AddFaceResponse。
【解决方案2】:

改进Kolky的答案,可以将反序列化的数据接收到数组中

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多