且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将json转换为列表?

更新时间:2023-01-17 19:41:16

我的文章中有一个帮助类在C#中使用JSON& VB [ ^ ]我测试了你的类和原始JSON样本进行反序列化并且工作正常。这是我的代码测试:

I have a helper class in my article Working with JSON in C# & VB[^] that I tested your classes and raw JSON sample to be deserialized and works fine. Here is my code test:
class Program
{
    static void Main(string[] args)
    {
        var rawJson = @"{""status"":""Ok"",""rows"":[{""elements"":[{""status"":""Ok"",""duration"":{""value"":10,""text"":""""},""distance"":{""value"":62,""text"":""۷۵ متر""}}]}],""origin_addresses"":[""35.724098,51.424491""],""destination_addresses"":[""35.724165,51.425121""]}";
        var result = JsonHelper.ToClass<Example>(rawJson);
    }
}

public class Duration
{
    public int value { get; set; }
    public string text { get; set; }
}

public class Distance
{
    public int value { get; set; }
    public string text { get; set; }
}

public class Element
{
    public string status { get; set; }
    public Duration duration { get; set; }
    public Distance distance { get; set; }
}

public class Row
{
    public IList<Element> elements { get; set; }
}

public class Example
{
    public string status { get; set; }
    public IList<Row> rows { get; set; }
    public IList<string> origin_addresses { get; set; }
    public IList<string> destination_addresses { get; set; }
}


public static class JsonHelper
{
    public static string FromClass<T>(T data, bool isEmptyToNull = false,
        JsonSerializerSettings jsonSettings = null)
    {
        string response = string.Empty;

        if (!EqualityComparer<T>.Default.Equals(data, default(T)))
            response = JsonConvert.SerializeObject(data, jsonSettings);

        return isEmptyToNull ? (response == "{}" ? "null" : response) : response;
    }

    public static T ToClass<T>(string data, JsonSerializerSettings jsonSettings = null)
    {
        var response = default(T);

        if (!string.IsNullOrEmpty(data))
            response = jsonSettings == null
                ? JsonConvert.DeserializeObject<T>(data)
                : JsonConvert.DeserializeObject<T>(data, jsonSettings);

        return response;
    }
}