简体   繁体   中英

How to deserialize json to custom type

I have the following json:

{
  "ExitCode": 1,
  "ErrorMessage": "",
  "NumberOfMatches": 9,
  "NumberOfExtractFrames": 3,
  "ProcessingTime": 111,
  "MatchResult": [
    {
      "TopLeft": "2, 8",
      "BottomRight": "377, 157",
      "Confidence": 1.0,
      "HighConfidenceLevel": true,
      "SearchFrame": "77, 69, 36, 26",
    },
    {
      "TopLeft": "2, 169",
      "BottomRight": "377, 318",
      "Confidence": 0.99999982118606567,
      "HighConfidenceLevel": true,
      "SearchFrame": "77, 230, 36, 26",
    },
...

and created classes:

public class JsonParse
{
    public int ExitCode { get; set; }
    public string ErrorMessage { get; set; }
    public int NumberOfMatches { get; set; }
    public int NumberOfExtractFrames { get; set; }
    public int ProcessingTime { get; set; }

    public List<MatchResult> MatchResult { get; set; }

}

public class MatchResult
{
    public Coordinate TopLeft { get; set; }
    public Coordinate BottomRight { get; set; }
    public decimal Confidence { get; set; }
    public bool HighConfidenceLevel { get; set; }
    //public Tuple<int, int, int, int> SearchFrame { get; set; }
}

public class Coordinate
{
    public int X { get; set; }
    public int Y { get; set; }
}

of course, it crashes when I try to do it:

_jsonParse = JsonConvert.DeserializeObject<JsonParse>(jsonParseString);

I try to create a converter:

public class CoordinateConverter : CustomCreationConverter<Coordinate>
{
    public override Coordinate Create(Type objectType)
    {
        return new Coordinate();
    }
}

and

_jsonParse = JsonConvert.DeserializeObject<JsonParse>(jsonParseString, new CoordinateConverter());

it does not work. How to declare and use a converter correct way?

I made it to create the following converter:

public class CoordinateConverter : CustomCreationConverter<Coordinate>
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var values = reader.Value.ToString().Split(',').Select(n => Convert.ToInt32(n)).ToArray();
        Coordinate coordinates = new Coordinate() { X = values[0], Y = values[1] };
        return coordinates;
    }

    public override bool CanConvert(Type objectType)
    {
        if (objectType == typeof(Coordinate))
        {
            return true;
        }

        return false;
    }

    public override Coordinate Create(Type objectType)
    {
        return new Coordinate();
    }
}

I use this class for all my objects:

public class JsonConverter
{
    public static string ObjectToString(object o)
    {
        var javaScriptSerializer = new JavaScriptSerializer();
        string jsonString = javaScriptSerializer.Serialize(o);

        return jsonString;
    }

    public static object StringToObject(string data)
    {
        var json_serializer = new JavaScriptSerializer();
        return json_serializer.DeserializeObject(data);
    }
}

To use it:

Coordinate co = new Coordinate(){ X=10,Y=20 }
string json = JsonConverter.ObjectToString(co);
Coordinate coParsed = (Coordinate)StringToObject(json);

And include

Namespace:   System.Web.Script.Serialization

And add reference too

Assembly:  System.Web.Extensions (in System.Web.Extensions.dll)

You can use this for any type of object in this example I used Coordinate because I could declare it simply.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM