在datagridview中显示JSON对象数组

时间:2017-01-09 17:16:41

标签: c# json

我试图解析JSON,我相信对象数组。我可以使用JObject.Parse解析简单的单个JSON,但是这个让我很头疼。

{
"2": {
  "num": 5,
  "average": 10,
  "state": true,
  "id": 2,
  "buy": 10,
  "name": "name"
 },
"6": {
  "num": 5,
  "average": 10,
  "state": true,
  "id": 6,
  "buy": 20,
  "name": "name"
 }
}

我有想法,但不知道如何在括号前处理数字。它始终与" id"相同。

我尝试使用Newtonsoft.Json这样的东西:

 List<Items> objlis = (List<Items>)Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(List<Items[]>));

然而它说&#34;该类型需要一个JSON数组(例如[1,2,3])才能正确反序列化。&#34;

2 个答案:

答案 0 :(得分:0)

您可以从Json构建如下表,然后调用datagridview

List<User> allusers = JsonConvert.DeserializeObject<List<User>>(jsonString);

public static DataTable MakeDataTable<T>(this IList<T> data)
        {
        PropertyDescriptorCollection props =
        TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        for(int i = 0 ; i < props.Count ; i++)
        {
        PropertyDescriptor prop = props[i];
        table.Columns.Add(prop.Name, prop.PropertyType);
        }
        object[] values = new object[props.Count];
        foreach (T item in data)
        {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        table.Rows.Add(values);
        }
        return table;        
    }

答案 1 :(得分:0)

看起来发送系统选择将稀疏列表序列化为JSON对象,其中对象名称是列表索引,而不是JSON数组。但是Json.NET maps JSON arrays from and to c# lists因此您对List<Items>的反序列化失败,并且异常消息该类型需要JSON数组(例如[1,2,3])才能正确反序列化。

反序列化此类JSON对象的最简单方法是dictionary,如Dictionary<string, Items>SortedDictionary<int, Items>,如this question所示,例如:

var dict = JsonConvert.DeserializeObject<SortedDictionary<int, Items>>(json);

如果您特别要求将JSON反序列化为列表,则可以编写custom JsonConverter来执行映射:

public class ListToDictionaryConverter<T> : JsonConverter where T : class
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(List<T>).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;
        var list = existingValue as List<T> ?? (List<T>)serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
        if (reader.TokenType == JsonToken.StartArray)
            serializer.Populate(reader, list);
        else if (reader.TokenType == JsonToken.StartObject)
        {
            var dict = serializer.Deserialize<Dictionary<int, T>>(reader);
            foreach (var pair in dict)
                list.SetOrAddAt(pair.Key, pair.Value, default(T));
        }
        else
        {
            throw new JsonSerializationException(string.Format("Invalid token {0}", reader.TokenType));
        }
        return list;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var list = (IList<T>)value;
        writer.WriteStartObject();
        for (int i = 0; i < list.Count; i++)
        {
            // Omit null values.
            if (list[i] == default(T))
                continue;
            writer.WritePropertyName(((JValue)i).ToString());
            serializer.Serialize(writer, list[i]);
        }
        writer.WriteEndObject();
    }
}

public static class ListExtensions
{
    public static void SetOrAddAt<T>(this IList<T> list, int index, T value, T defaultValue = default(T))
    {
        if (list == null)
            throw new ArgumentNullException("list");
        list.EnsureCount(index + 1, defaultValue);
        list[index] = value;
    }

    public static void EnsureCount<T>(this IList<T> list, int count, T defaultValue = default(T))
    {
        if (list == null)
            throw new ArgumentNullException("list");
        int oldCount = list.Count;
        if (count > oldCount)
        {
            for (int i = oldCount; i < count; i++)
                list.Add(defaultValue);
        }
    }
}

然后使用它:

var objlis = JsonConvert.DeserializeObject<List<Items>>(json, new ListToDictionaryConverter<Items>());

示例fiddle