JSON.NET反序列化在空对象,C#结果 [英] JSON.NET Deserialization in C# results in empty object

查看:491
本文介绍了JSON.NET反序列化在空对象,C#结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图填充一个C#对象(ImportedProductCodesContainer)使用JSON.NET反序列化的数据。

I am trying to populate a C# object (ImportedProductCodesContainer) with data using JSON.NET deserialization.

ImportedProductCodesContainer.cs:

ImportedProductCodesContainer.cs:

using Newtonsoft.Json;

[JsonObject(MemberSerialization.OptOut)]
public class ImportedProductCodesContainer
{
    public ImportedProductCodesContainer()
    {

    }

    [JsonProperty]
    public ActionType Action { get; set; }

    [JsonProperty]
    public string ProductListRaw { get; set; }


    public enum ActionType {Append=1, Replace};
}



JSON字符串:

JSON string:

{"ImportedProductCodesContainer":{"ProductListRaw":"1 23","Action":"Append"}}

C#代码:

 var serializer = new JsonSerializer();
 var importedProductCodesContainer = 
     JsonConvert.DeserializeObject<ImportedProductCodesContainer>(argument);



问题是, importedProductCodesContainer 的运行上面的代码后,保持为空(动作= 0,ProductListRaw = NULL)。你可以帮我找出什么是错的?

The problem is that importedProductCodesContainer remains empty after running the code above (Action = 0, ProductListRaw = null). Can you please help me figure out what's wrong?

推荐答案

您有一个层次过多 ImportedProductCodesContainer 。它创建一个新的 ImportedProductCodesContainer 对象(从模板解串器),然后尝试设置属性就可以了名为 ImportedProductCodesContainer (从你的JSON的顶层),这将是含有其他两个值的结构。如果反序列化内部唯一

You have one too many levels of ImportedProductCodesContainer. It's creating a new ImportedProductCodesContainer object (from the templated deserializer) and then attempting to set a property on it called ImportedProductCodesContainer (from the top level of your JSON) which would be a structure containing the other two values. If you deserialize the inner part only

{"ProductListRaw":"1 23","Action":"Append"}

那么你应该得到你期待的对象,也可以创建与ImportedProductCodesContainer属性新的结构

then you should get the object you're expecting, or you can create a new struct with an ImportedProductCodesContainer property

[JsonObject(MemberSerialization.OptOut)]
public class ImportedProductCodesContainerWrapper
{
    [JsonProperty]
    public ImportedProductCodesContainer ImportedProductCodesContainer { get; set; }
}

和与那么你原来的JSON应该工作模板您解串器。

and template your deserializer with that then your original JSON should work.

这也可能是可以使用其他属性/标志与JSON库来改变这种行为,但我不知道它不够好再说。

It may also be possible to change this behaviour using other attributes / flags with that JSON library but I don't know it well enough to say.

这篇关于JSON.NET反序列化在空对象,C#结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆