2017-04-03 107 views
0

使用C#,反序列化动态JSON对象的正确方法是什么(即:某个JSON可以在对象之间更改单个键的类型)?自定义动态JSON反序列化

例如,如果我有这样的(完全有效的)JSON:

{ 
    "stuffs": [ 
    { "content": "abcd" }, 
    { "content": "efgh" }, 
    { "content": [ 
     "ijkl", 
     "mnop" 
    ]} 
    ] 
} 

其中thing可以是字符串或字符串数​​组,如何反序列化这一点,如果我已经定义这些类?

class ThingContainer { 
    List<Thing> stuffs; 
} 

class Thing { 
    List<string> content; 
} 

试图反序列化I(果然)碰到一个例外:

Newtonsoft.Json.JsonSerializationException:“不能反序列化JSON当前对象(例如{ “名”: “值” })类型'System.Collections.Generic.List`1 [DummyProject.Thing]'

+1

http://stackoverflow.com/questions/18994685/how-to-handle-both-a-single-item-and-an-array-for-the-same-property-using-json-n此帖子将帮助您设计解决方案。 – Sameer

+0

@Sameer谢谢,我不知道我在搜索现有问题时没有发现。我想我做了一个重复。 –

回答

0

你的问题是,你的C#类不能准确地代表JSON。

您的JSON有一个对象,其中包含一个对象“东西”,对象列表“内容”是一个字符串列表。

你在C#类中有什么是一个对象,它包含一个对象是一个字符串列表。

您需要一个包含对象的对象,该对象是包含字符串列表的对象列表。

试试这个:

public class Content 
{ 
    public List<string> Content { get; set; } 
} 

public class Stuff 
{ 
    public List<Content> Contents { get; set; } 
} 

public class ThingContainer 
{ 
    public List<Stuff> Stuffs { get; set; } 
} 
+0

这不适用于示例数组中的最后一个条件/条目,可能是将反序列化为列表的自定义格式化程序/反序列化程序,即使它是扁平结构中的一个项目也是如此? –

+1

我注意到它的最后一项要求是列表并更新了我的回复。 –

0

我不知道是否有在C#中的任何解决方案,但我recomended你adapte您的JSON结构,如:

{ 
    arrayStuffs[ 
    { content: ['123', '456'] }, 
    // another arrays... 
    ], 
    stringStuffs{ 
    content: '', 
    // another strings.. 
    }, 
    // another stuffs, and so on 
} 

,并定义一个模型,所有的东西:

public class arrayStuff{ 
    List<string> content; 
} 
0

我不确定这是否可以用NewtonSoft完成,但如果你回到Windows中的内置API .Data.Json你可以获得你想要的任何灵活性。