反序列化对象列表

时间:2018-11-27 04:46:52

标签: c# json parsing serialization request

我是C#的新手,我想从heroku中的应用程序获取JSON。在我用javascript完成它之前,没有任何问题,但是现在我正在尝试在C#中完成它。 我的代码是:

namespace FirstApp
{
    public class AOA
    {
        public Data data { get; set; }

        public static void Main()
        {
            var json = string.Empty;
            var aoa = new List<AOA>();
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"http://beautyglam.herokuapp.com/aoa/eyeliner?page=1");
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream);

                json = reader.ReadToEnd();
                aoa = JsonConvert.DeserializeObject<List<AOA>>(json);

                Console.WriteLine("DATOS");
                Console.WriteLine(json);
                Console.WriteLine(aoa[0].data);
            }
            catch(Exception e)
            {
                Console.WriteLine("Errorrr: " + e);
            }
        }
    }

    public class Data
    {
        public string category { get; set; }
        public int pages { get; set; }
        public string name { get; set; }
        public int? price { get; set; }
        public string id { get; set; }
        public string img { get; set; }
    }
}

返回的json类似于:

[{"category":"AOA Eye Liner","pages":0},{"name":"AOA Starlet Eyeliner- Spotlight","price":150,"id":"751612657678","img":"//cdn.shopify.com/s/files/1/0882/6874/products/AOA-164-MAIN_large.jpg?v=1539192189"},{"name":"AOA Starlet Eyeliner- Hollywood","price":150,"id":"751612592142","img":"//cdn.shopify.com/s/files/1/0882/6874/products/AOA-166-MAIN_large.jpg?v=1539192156"},{"name":"AOA Starlet Eyeliner- Fame","price":150,"id":"751612559374","img":"//cdn.shopify.com/s/files/1/0882/6874/products/AOA-169-MAIN_large.jpg?v=1539192087"},{"name":"AOA Starlet Eyeliner- Superstar","price":150,"id":"751612526606","img":"//cdn.shopify.com/s/files/1/0882/6874/products/AOA-167-MAIN_large.jpg?v=1539192203"},{"name":"AOA Starlet Eyeliner- Paparazzi","price":150,"id":"751612461070","img":"//cdn.shopify.com/s/files/1/0882/6874/products/AOA-165-MAIN_large.jpg?v=1539192338"},{"name":"AOA Starlet Eyeliner- Golden Girl","price":150,"id":"751612329998","img":"//cdn.shopify.com/s/files/1/0882/6874/products/AOA-168-MAIN_large.jpg?v=1539192127"},{"name":"AOA Wonder Liquid Liner - Black","price":150,"id":"194917793806","img":"//cdn.shopify.com/s/files/1/0882/6874/products/AOA-036-1_large.jpg?v=1522944978"},{"name":"AOA Wonder Liquid Liner - Dark Brown","price":150,"id":"194917335054","img":"//cdn.shopify.com/s/files/1/0882/6874/products/AOA-037-1_large.jpg?v=1522944879"}]

我想像在Javascript中一样使用它,例如:

aoa[0].name;

1 个答案:

答案 0 :(得分:0)

您的json结构的类表示对于您的示例无效。另外,您的json结构需要使用一些特殊的反序列化器进行解析,因为它不包含包含值。

您有一个json对象数组,但它们的类型不同。

您需要3个类,一个代表类别和页面,一个代表名称,价格,id,img,一个代表包含这两个类的根。

这是它的外观:

class RootObj {
    public Category category { get; set; }
    public List<Detail> details { get; set; }
}

class Category {
    public string category { get; set; }
    public int pages { get; set; }
}

class Detail {
    public string name { get; set; }
    public int price { get; set; }
    public string id { get; set; }
    public string img { get; set; }
}

这是自定义反序列化器:

class CustomObjectConverter<T> : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JArray array = JArray.Load(reader);

        RootObj result = new RootObj();

        result.category = array[0].ToObject<Category>();
        array.RemoveAt(0);
        result.details = array.ToObject<List<Detail>>();

        return result;
    }

    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(RootObj));
    }
}

主要:

string jsonText = File.ReadAllText("json.txt");

var deserializer = new JsonSerializerSettings();
deserializer.Converters.Add(new CustomObjectConverter<RootObj>());

var result = JsonConvert.DeserializeObject<RootObj>(jsonText, deserializer);

现在,您可以按以下方式访问属性:

Console.WriteLine(result.category.category);

输出为:

AOA Eye Liner

您可以根据自己的用例对其进行自定义。