【问题标题】:C# JSON.NET invalid typeC# JSON.NET 无效类型
【发布时间】:2015-03-05 09:21:21
【问题描述】:

我正在为 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}

【问题讨论】:

  • 原来的类名是什么,或许我们可以从中推断出发生了什么
  • 类名不能是数字
  • 类名的开头不能使用数字,例如添加_符号。
  • @Aviatrix 对象在某个时间已经序列化为json。这意味着要么类名是一个不可能的数字,要么类名已被篡改。在这两种情况下,我认为他已经知道类名不应该是数字。
  • 原来的类名就像上面一样。只是 RootObject 是由生成器生成的。当我添加 _ 时,反序列化将不起作用!

标签: c# json class


【解决方案1】:

看起来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。

【讨论】:

  • 非常感谢!完美运行!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多