【问题标题】:How to convert php->json to c# class?如何将 php->json 转换为 c# 类?
【发布时间】:2014-10-10 03:28:48
【问题描述】:

我正在尝试反序列化对 C# 类的 json 响应。 问题是元素被命名为"1" , "2" 等,在转换为C# 类时会产生问题,因为变量不能命名为"1"。 如果没有相同的变量名,反序列化似乎不起作用。

我的数组是这样的:

[{
    "0": "21838",
    "1": "2014-10-15",
    "2": "2014-10-15",
    "3": "745",
    "4": "140.00",
    "32": "140.00",
    "5": "140.00",
    "33": "140.00",
    "7": "0.00",
    "34": "0.00",
    "35": 0,
    "8": "30",
    "9": "10",
    "10": "6",
    "11": "0",
    "12": "0000-00-00",
    "13": "0.00",
    "36": "",
    "14": "1833",
    "15": "1",
    "16": "1",
    "17": "184",
    "18": "305",
    "19": "1",
    "20": "2264",
    "21": "3214",
    "22": {"0":"123"}
    /* etc, etc, etc */
}]

如何将其反序列化为 C# 类? *更新,json有数组数组

【问题讨论】:

    标签: c# php json serialization json.net


    【解决方案1】:

    您应该能够使用JavaScriptSerializer 反序列化为字典数组。

    var json = "bla bla bla json";
    
    var dictionaries = new JavaScriptSerializer()
        .Deserialize<Dictionary<string, string>[]>(json);
    
    foreach (var dictionary in dictionaries)
    {
        foreach (var pair in dictionary)
        {
            Console.WriteLine("{0} => {1}", pair.Key, pair.Value);
        }
    }
    
    Console.WriteLine(dictionaries[0]["0"]); // 21838
    

    【讨论】:

    • 感谢 Mathew 的回复,我尝试使用您的解决方案,但它显示“在 JSON 反序列化期间没有为 'System.String' 类型定义无参数构造函数”我尝试使用抛出相同的 Newtonsoft.Json例外。
    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    • 2022-12-12
    • 2021-09-08
    • 1970-01-01
    相关资源
    最近更新 更多