序列化时使用特定的属性名称和Json.NET

时间:2014-04-17 12:04:43

标签: c# json json.net

在C#中使用Json.NET,在序列化类时遇到麻烦,我需要一个自定义属性名称。

这就是我现在所拥有的:

{
  "baseName": {
    "subName1": {
      "name": null,
      "longName": null,
      "asd1": null,
      "asd2": null
    },
    "subName2": [
      {
        "id": "ID_NUMBER",
        "info": {
          "someInfo1": "asd",
          "someInfo2": "asd2"
        }
      }
    ]
  }
}

这就是我想要的

{
  "baseName": {
    "subName1": {
      "name": null,
      "longName": null,
      "asd1": null,
      "asd2": null
    },
    "subName2": [
      {
        "ID_NUMBER": {
          "someInfo1": "asd",
          "someInfo2": "asd2"
        }
      }
    ]
  }
}

也就是说,我希望id不是拥有ID_NUMBER和值ID_NUMBER的密钥,而是包含密钥someInfo1和{的对象的密钥。 {1}}。

使用这些类生成顶级JSON代码(对不好的名称抱歉):

someInfo2

而且:

class JSONTestClass
{
    public JSONBaseTestClass baseName;
}

class JSONBaseTestClass
{
    public JSONSubTestClass1 subName1;
    public List<JSONSubTestClass2> subName2;
}

class JSONSubTestClass1
{
    public string name;
    public string longName;
    public string asd1;
    public string asd2;
}

class JSONSubTestClass2
{
    public string id;
    public JSONInfoTestClass info;
}

class JSONInfoTestClass
{
    public string someInfo1;
    public string someInfo2;
}

需要进行哪些更改,以便获得与上述第二个JSON响应相对应的JSON输出?

1 个答案:

答案 0 :(得分:1)

您可以为JsonConverter类创建自定义JSONSubTestClass2,从而获得所需的输出:

class JSONSubTestClass2Converter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(JSONSubTestClass2));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        JSONSubTestClass2 jstc2 = (JSONSubTestClass2)value;
        JObject jo = new JObject();
        jo.Add(jstc2.id, JObject.FromObject(jstc2.info));
        jo.WriteTo(writer);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

然后,像这样序列化您的类:

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new JSONSubTestClass2Converter());
settings.Formatting = Formatting.Indented;

// Convert to JSON
string json = JsonConvert.SerializeObject(jtc, settings);