De-serializing json format string

时间:2018-07-24 10:13:33

标签: c# string websocket deserialization

Currently I have a websocket application that receives response from the server.

I am using

object obj=new JavaScriptSerializer().Deserialize<CustomerNTF>(e.data);

to deserialize the json string.

The string that I am supposed to de-serialize is:

{
  "face_list":[
      {
         "face_detect":{
              "age":65535,
              "beauty":65535,
              "expression":65535,
              "gender":65535,
              "glass":false,
              "smile":65536
           },
           "face_recg":{
           "confidence":82,
           "name":"user",
           "person_id":"person1"
        }
       }
     ],
    "face_num":1,
    "msg_id":"FACE_DETECT"
}

What I have tried:

public class CustomerNTF
{
    public face_list face_list { get; set; }
    public int face_num{get;set;}
    public string msg_id{get;set;}
}
public class face_list
{
    public class face_detect
    {
        public int age { get; set; }
        public int beauty { get; set; }
        public int expression { get; set; }
        public int gender { get; set; }
        public bool glass { get; set; }
        public int smile { get; set; }
    }
    public class face_recg
    {
        public int confidence { get; set; }
        public string name { get; set; }
        public string person_id { get; set; }
    }
}

The error I am receiving is that the deserialization of arrays does not support the type face_list.

1 个答案:

答案 0 :(得分:0)

Your class structure is wrong. The json string contains a list of face_list not a single object. Furthermore your current face_list class does not contain any properties just two nested class definitions which will not hold any values.

Correct structure:

public class FaceDetect
{
    public int age { get; set; }
    public int beauty { get; set; }
    public int expression { get; set; }
    public int gender { get; set; }
    public bool glass { get; set; }
    public int smile { get; set; }
}

public class FaceRecg
{
    public int confidence { get; set; }
    public string name { get; set; }
    public string person_id { get; set; }
}

public class FaceList
{
    public FaceDetect face_detect { get; set; }
    public FaceRecg face_recg { get; set; }
}

public class CustomerNTF
{
    public List<FaceList> face_list { get; set; }
    public int face_num { get; set; }
    public string msg_id { get; set; }
}

In the future if you are not sure how your class structure has to look like to match a given json string you can use a tool like json2csharp. Which generates the correct structure for you.