JSON.Net 反序列化返回“null”

2024-05-21

我正在使用 JSON.Net 反序列化 JSON 字符串。 JSON 字符串是

string testJson = @"{
                    ""Fruits"": {
                        ""Apple"": {
                            ""color"": ""red"",
                            ""size"": ""round""                               
                        },
                        ""Orange"": {
                            ""Properties"": {
                                ""color"": ""red"",
                                ""size"": ""round"" 
                            }
                        }
                    }
                }";

我的代码是

public class Fruits
{
    public Apple apple { get; set; }
    public Orange orange { get; set; }
}

public class Apple
{
    public string color { get; set; }
    public string size { get; set; }            
}

public class Orange
{
    public Properties properties { get; set; }
}

public class Properties
{
    public string color { get; set; }
    public string size { get; set; }   
}   

我正在尝试使用以下代码反序列化它

Fruits result = JsonConvert.DeserializeObject<Fruits>(testJson);

我的系统有问题result that Fruits with Apple and Orange has null而不是他们的特性 , color , size.


假设你不能改变json,你需要创建一个新的FruitsWrapper类有一个Fruits财产

public class FruitsWrapper
{
    public Fruits Fruits { get; set; }
}

并将 json 反序列化为实例FruitsWrapper代替Fruits

FruitsWrapper result = JsonConvert.DeserializeObject<FruitsWrapper>(testJson);

工作演示:https://dotnetfiddle.net/nQitSD https://dotnetfiddle.net/nQitSD

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JSON.Net 反序列化返回“null” 的相关文章

随机推荐