C# Deserialize JSON string into object using Newtonsoft.Json

10,733

Solution 1

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

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

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

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

Solution 2

Improving the answer of Kolky, you can receive the deserializated data to an array

    Face[] faces = JsonConvert.DeserializeObject<Face[]>(responseContentStr);
Share:
10,733
EricMA
Author by

EricMA

Updated on June 04, 2022

Comments

  • EricMA
    EricMA almost 2 years

    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);
    

    this is the json string responseContentStr

    [{
        "faceId": "1fe48282-a3b0-47d1-8fa8-67c4fac3d984",
        "faceRectangle": {
            "top": 80,
            "left": 50,
            "width": 147,
            "height": 147
        }
    }]
    

    This is my model object.

    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;
            }
        }
    

    this is the error I am getting from 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

    • Travis J
      Travis J over 6 years
      Where is the definition of the IdentifyResponse class.
    • EricMA
      EricMA over 6 years
      sorry I copied the wrong line of code. I intend to convert the string into AddFaceResponse. I just update it. @TravisJ
  • EricMA
    EricMA over 6 years
    Sorry for the confusion, I copied the wrong line of code. I am trying to convert it into AddFaceResponse.