c # Как преобразовать данные Json в объекты - PullRequest
1 голос
/ 06 октября 2011

Я пытаюсь проанализировать некоторые JSON с помощью библиотеки Newtonsoft.Json.Документация кажется немного скудной, и я не понимаю, как выполнить то, что мне нужно.Вот формат для JSON, который мне нужно проанализировать.

const string json = @"{   ""error"" : ""0"", 
""result"" :
{
   ""1256"" : {
      ""data"" : ""type any data"", 
      ""size"" : ""12345""
   },
   ""1674"" : {
      ""data"" : ""type any data"", 
      ""size"" : ""12345""
   },
   // ... max - 50 items
}
}";

Я пытаюсь преобразовать данные JSON в какой-то хороший объект.Вот мой класс:

public class ListLink
{
    public String data{ get; set; }
    public String size { get; set; }
}

public class SubResult
{
    public ListLink attributes { get; set; }
}

public class Foo
{
    public Foo() { results = new List<SubResult>(); }
    public String error { get; set; }
    public List<SubResult> results { get; set; }
}
.....
List<Foo> deserializedResponse =  
    (List<Foo>)Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(List<Foo>));

Но я всегда получаю ошибку.Любые идеи?

РЕДАКТИРОВАТЬ: я получаю сообщение об ошибке:

Newtonsoft.Json.JsonSerializationException: Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[ConsoleApplication1.Foo]' (...)

Ответы [ 2 ]

0 голосов
/ 06 октября 2011

Это немного уродливо, но может удовлетворить ваши потребности Он также не использует стороннее решение. Извинения, если это немного kludgey!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

const string json = @"{   ""error"" : ""0"", 
                            ""result"" :
                            {
                               ""1256"" : {
                                  ""data"" : ""type any data"", 
                                  ""size"" : ""123456""
                               },
                               ""1674"" : {
                                  ""data"" : ""type any data"", 
                                  ""size"" : ""654321""
                               },
                               ""1845"" : {
                                  ""data"" : ""type any data"", 
                                  ""size"" : ""432516""
                               },
                                ""1956"" : {
                                  ""data"" : ""type any data"", 
                                  ""size"" : ""666666""
                               }
                            }
                            }";

JavaScriptSerializer j = new JavaScriptSerializer();

var x = (Dictionary<string, object>)j.DeserializeObject(json);

Foo foo = new Foo();

foo.error = x["error"].ToString();

foreach (KeyValuePair<string, object> item in (Dictionary<string, object>)x["result"])
{

    SubResult result = new SubResult();

    ListLink listLink = new ListLink();

    var results = (Dictionary<string, object>)item.Value;

    foreach (KeyValuePair<string, object> sub in results)
    {

        listLink.data = results.First().Value.ToString();
        listLink.size = results.Last().Value.ToString();

    }

    SubResult subResult = new SubResult { attributes = listLink };

    foo.results.Add(subResult);

}
0 голосов
/ 06 октября 2011

Пример:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public struct Element {
    public string data{ get; set; }
    public int size { get; set; }
}

class Sample {
    static public void Main(){
        const string json =
        @"{ ""error"" : ""0"", 
            ""result"" :
            {
               ""1256"" : {
                  ""data"" : ""type any data(1256)"", 
                  ""size"" : ""12345""
               },
               ""1674"" : {
                  ""data"" : ""type any data(1674)"", 
                  ""size"" : ""45678""
               },
            }
        }";
        dynamic obj =  JsonConvert.DeserializeObject(json);
        int error = obj.error;
        Console.WriteLine("error:{0}", error);
        dynamic result = obj.result;
        Dictionary<string, Element> dic = new Dictionary<string, Element>();
        foreach(dynamic x in result){
            dynamic y = x.Value;
            dic[x.Name] = new Element { data = y.data, size = y.size};
        }
        //check
        Element el = dic["1674"];
        Console.WriteLine("data:{0}, size:{1}", el.data, el.size);
        el = dic["1256"];
        Console.WriteLine("data:{0}, size:{1}", el.data, el.size);
    }
}

ВЫВОД:

error:0
data:type any data(1674), size:45678
data:type any data(1256), size:12345
...