C#、JSON Class 动态属性上的序列化程序和反序列化程序

C# , JSON Serializer and Deserializer on Class Dynamic Attributes

您好,我有一个现有的 class 称为属性(如下),带有一组基本的静态属性。我正在使用此 class 通过 JavaScriptSerializer

进行序列化和反序列化
public class attributes
{
public string static1 {get; set;}
public string static2 {get; set;}
public string static3 {get; set;}
}

我当前的示例 JSON 基于上述 class 属性

{
  "static1": "val1",
  "static2": "val2",
  "static3": "val3"
}

我需要对我的 class 进行修改,以便保留基本集并扩展此 class 以接受新格式。我将从供应商那里收到一个新的 JSON,他们将在其中附加属性的动态部分(在我的示例 JSON 下面,从 1 到 N)。这样,现有的静态属性基本集将可以访问,并且还提供动态属性列表(可以从 0 到 n - 这意味着如果没有其他可用属性,它可以与静态属性相同 JSON或者可以有3个静态属性+一些其他附加属性)

新 JSON 静态和动态

{
  "static1": "val1",
  "static2": "val2",
  "static3": "val3",
  "dynamic1": "dyn1",
           .
           .
  "dynamicN": "dynN"
}

鉴于新要求(我们可能在 JSON 我获得的属性中有更多属性),任何人都可以提供一些关于如何最好地表示这个新 class 的意见吗?

谢谢

您可以尝试执行 dynamic 对象来手动解析您的 json 结果。

像这样(使用 Newtonsoft.Json):

dynamic json = JsonConvert.DeserializeObject(jsonResult);
foreach (dynamic item in json)
{
   //manually get the values
   var static1= item["static1"];
   var static2= item["static2"];
   .......
}

您可以使用 dynamics type variable 获取未映射到 class

中的 JSON 的信息
var json = new JavaScriptSerializer();
string data = "{ "+
"\"0\": {" +
"   \"sku\": \"trickeye\", " +
"   \"calendar_type\": \"date\", " +
"   \"voucher_type\": \"Instant Voucher\"   " +
"},"+
" \"1\": { " +
"   \"sku\": \"lovemuseum\", " +
"   \"calendar_type\": \"date\", " +
"   \"voucher_type\": \"Instant Voucher\"} " +
"}";
dynamic dictionary = json.DeserializeObject(data);

var firstDefinition = dictionary["0"] as Dictionary<string, object>;

Console.WriteLine(firstDefinition);
Console.WriteLine(dictionary["0"]["sku"].ToString());