如何使用C#解析JSON对象与另一个对象childen

时间:2016-04-13 00:54:18

标签: c# arrays json getjson

我需要属性对象的属性名称:

这是我的代码:

JSON示例:

 {
"dados":      [{"codigo_localidade":"1",
"localidade":"Adamantina",
"nome_localidade_pai":"Regi\u00e3o de Governo de Adamantina",
"codigo_variavel":"2",
"variavel":"Cr\u00e9dito Rural Agricultura",
"unidade":"(Em reais de 2015)",
"periodo":"1985\/1989-2011",
"ano":{"2010":"194.140.750"}
}

我的C#CODE来解析我的JSON:

  var resultObjects = AllChildren(JObject.Parse(cidadesSON))
                     .First(c => c.Type == JTokenType.Array && c.Path.Contains("dados"))
                     .Children<JObject>();

                    List<Cidade> cidades = new List<Cidade>();
                    Cidade item;
//fetch my array 
                    foreach (JObject result in resultObjects)
                    {
                        item = new Cidade();
                        item.localidade =(string)result["localidade"];
                        item.nome_localidad_pai =    (string)result["nome_localidade_pai"];
                        item.populacao = (string)result["ano"]["2010"];

                        //my problem
                        item.ano = ((JObject)result.["ano"]).Property("2010").Name;

                     cidades.Add(item);

                    }



                    grvCandidatos.DataSource = cidades;
                    grvCandidatos.CssClass = "table table-hover ";
                    grvCandidatos.DataBind();

这是获取对象的方法

private static IEnumerable<JToken> AllChildren(JToken json)
        {
            foreach (var c in json.Children())
            {
                yield return c;
                foreach (var cc in AllChildren(c))
                {
                    yield return cc;
                }
            }
        }

如有必要,这是我的Model类:

public class Cidade
        {
            public string localidade { get; set; }
            public string populacao { get; set; }
            public string nome_localidad_pai { get; set; }
            public string ano { get; set; }

        }

如果有人可以提供帮助,我将非常感激。

(抱歉我的英文。)

2 个答案:

答案 0 :(得分:0)

使用以下方法从NSData解析JSON

   func parseJSON(data: NSData) -> ([String : AnyObject]?, NSError?) {

        var parsingError: NSError? = nil
        let parsedResult: [String : AnyObject]?
        do {

            parsedResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? [String : AnyObject]
        } catch let error as NSError {

            parsingError = error
            parsedResult = nil
        }
        return (parsedResult, parsingError)
    }

如果您在NSData中没有JSON 使用以下函数将JSON转换为NSData:

func jsonToNSData(json: AnyObject) -> NSData?{
    do {
        return try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
    } catch let myJSONError {
        print(myJSONError)
    }
    return nil;
}

答案 1 :(得分:0)

<强> TL; DR

您的代码存在的问题是我们不知道ano属性的类型是什么。您可以将该属性映射到Dictionary<string,object>,并通过访问Dictionary的Key属性来获取实际的ano。 请参阅下面的示例,了解如何执行此操作:

假设您可以在程序中使用第三方库,只需将Json.Net添加到项目中,就可以将所有代码减少到此:

“Dado”类

public class Dado
{
    public string localidade { get; set; }
    public string populacao { get; set; }
    public string nome_localidad_pai { get; set; }

    [JsonConverter(typeof(AnoConverter))]
    public string ano { get; set; }
}

“Root”类

public class RootObject
{
    public List<Dado> dados { get; set; }
}

然后,您可以创建自定义 JsonConverter 来操作json的反序列化:

public class AnoConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        //This deserialize the Ano into a Dictionary,
        //and returns the Key that contains the actual Year you want

        var ano  = serializer.Deserialize<Dictionary<string, object>>(reader);

        //I'm assuming that there will be always one year here.
        return ano.FirstOrDefault().Key;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

现在在你的程序中,只需将你的json反序列化为强类型类:

//Just reading the json from a file, nothing new here...
string json = String.Empty;
using (StreamReader r = new StreamReader("example.json"))
{
    json = r.ReadToEnd();
}

//Deserialize in json into a "RootObject"
var list = JsonConvert.DeserializeObject<RootObject>(json);

这会给你一个这样的结果: enter image description here

注意 您可以为populacao字段创建自定义JsonConverter的相同过程,但不是访问密钥,而是访问该值。同样的逻辑。我没有故意这样做,所以你可以自己做,并学习:)