相关疑难解决方法(0)

使用JSON.NET将异构JSON数组反序列化为协变List <>

我有一个JSON数组,包含具有不同属性的不同类型的对象.其中一个属性称为"类型",它确定数组项的类型.以下是我的数据示例:

   [{
        type : "comment",
        text : "xxxx"
    }, {
        type : "code",
        tokens : [{
                type : "ref",
                data : "m"
            }, {
                type : "operator",
                data : "e"
            }
        ]
    }, {
        type : "for",
        boundLocal : {
            type : "local",
            name : "i",
            kind : "Number"
        },
        upperBound : {
            type : "ref",
            tokens : [{
                    type : "operator",
                    data : "3"
                }, {
                    type : "operator",
                    data : "0"
                }
            ]
        },
        body : [{
                type …
Run Code Online (Sandbox Code Playgroud)

c# json json.net deserialization

39
推荐指数
1
解决办法
1万
查看次数

将JSON反序列化为多个C#子类之一

我有一个看起来像这样的json结构:

"list":[
  {
    "type":"link",
    "href":"http://google.com"
  },
  {
    "type":"image",
    "src":"http://google.com/logo.png"
  },
  {
    "type":"text",
    "text":"some text here"
  },
]
Run Code Online (Sandbox Code Playgroud)

我想将其反序列化为对象列表,其中每个对象都是基类的子类.列表中的每个项目都有不同的属性(href,src,text),因此我不能使用相同的类来获取一个.相反,我想要一个普通类的三个子类.JSON列表中每个项的type属性可用于决定使用哪个子类.例如,我可以拥有以下类

public Item{
  public string type {get; set;}
}
public LinkItem : Item {
  public string href {get; set;}
}
public ImageItem : Item {
  public string src {get; set;}
}
public TextItem : Item {
  public string text {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?或者是否有更好的方法来反序列化异构对象类型列表?

编辑:

我顺便使用json.net

c# inheritance json deserialization

10
推荐指数
1
解决办法
3013
查看次数

标签 统计

c# ×2

deserialization ×2

json ×2

inheritance ×1

json.net ×1