C#使用Newtonsoft.Json将JSON字符串反序列化为对象 [英] C# Deserialize JSON string into object using Newtonsoft.Json

查看:234
本文介绍了C#使用Newtonsoft.Json将JSON字符串反序列化为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Newtonsoft.json将json字符串转换为对象,但是以下转换存在一些问题.我不知道有人能解释这一点.谢谢.

I am trying to convert a json string to an object using Newtonsoft.json, but I am having some problems with the following conversion. I wonder if some one can explain this. thanks.

AddFaceResponse ir = JsonConvert.DeserializeObject<AddFaceResponse>(responseContentStr);

这是json字符串responseContentStr

this is the json string 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中得到的错误.

this is the error I am getting from visual studio.

Newtonsoft.Json.JsonSerializationException:无法将当前JSON数组(例如[1,2,3])反序列化为type 'App2.AddFaceResponse',因为该类型需要JSON对象(例如 {"name":"value"})正确反序列化

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

推荐答案

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

You are deserializing an array into an object. You could get it to work with;

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

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

Or wrap your JSON string with another pair of accolades { }, and add a property;

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

这篇关于C#使用Newtonsoft.Json将JSON字符串反序列化为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆