繁体   English   中英

C#JSON.NET无效类型

[英]C# JSON.NET invalid type

我目前正在为Windows Phone开发一个雷暴应用程序,但是我有一个问题。

当我将JSON字符串转换为C#类时,我发现类名称仅包含数字。

如何反序列化JSON字符串?

    public class 904
    {
        public string id { get; set; }
        public string name { get; set; }
        public string name_url { get; set; }
        public string region_path { get; set; }
    }

    public class Result
    {
        public 904 904 { get; set; }
    }

    public class RootObject
    {
        public bool status { get; set; }
        public Result result { get; set; }
        public int time_valid_to { get; set; }
    }

JSON字符串

    {"status":true,"result":{"904":{"id":"904","name":"Wien Alsergrund","name_url":"wien_alsergrund","region_path":"oesterreich\/wien\/wien_alsergrund"}},"time_valid_to":1424978715}

看起来result属性实际上是结果的映射-因此您可以使用Dictionary<,>表示它。 这有效:

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

public class ResultEntry
{
    public string id { get; set; }
    public string name { get; set; }
    public string name_url { get; set; }
    public string region_path { get; set; }
}


public class RootObject
{
    public bool status { get; set; }
    public Dictionary<int, ResultEntry> result { get; set; }
    public int time_valid_to { get; set; }
}

class Test
{
    static void Main()
    {
        string json = File.ReadAllText("json.txt");
        var root = JsonConvert.DeserializeObject<RootObject>(json);
        Console.WriteLine(root.result[904].name);
    }
}

我强烈建议使用更干净的属性名称并指定属性,以告诉Json.NET如何将它们映射到JSON。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM