簡體   English   中英

如何將json反序列化為自定義類型

[英]How to deserialize json to custom type

我有以下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",
    },
...

並創建類:

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

當然,當我嘗試這樣做時會崩潰:

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

我嘗試創建一個轉換器:

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

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

這是行不通的。 如何聲明和使用轉換器正確的方式?

我創建了以下轉換器:

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

我將此類用於所有對象:

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

要使用它:

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

並包括

Namespace:   System.Web.Script.Serialization

並添加參考

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

在本例中,您可以將其用於任何類型的對象,因為我可以簡單地聲明它,所以使用了Coordinate。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM