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

标签 c# json serialization json.net

我正在尝试使用 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: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'App2.AddFaceResponse' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly

最佳答案

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

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

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

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

关于C# 使用 Newtonsoft.Json 将 JSON 字符串反序列化为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45682446/

相关文章:

C# OpenXML 判断段落是否为隐藏文本

c# - 如何获取 Windows 服务登录凭据

jQuery 循环从 AJAX 成功的 JSON 结果?

c# - EndOfStreamException 与简单的 BinaryWriter 和 BinaryReader

c# - 在数据成员 "__type"上反序列化 JSON 时出现问题

c# - 使用 JsonConverter 的 OnDeserialized 回调

c# - 对同一 http 主机的多个同时请求

java - Gson 。将整数反序列化为整数而不是 double

json - 编码结构 slice 时向生成的 JSON 添加外部标记

javascript - 在javascript中获取2个字符之间的子字符串