7

我正在使用 JSON.NET 反序列化我拥有的一些 JSON 响应。到目前为止,我一直很成功。为了让 JSON.NET 正确反序列化对象,类中的字段名称需要与 JSON 中的完全一致。问题是我有一些字段名称中包含我不能在 C# 中使用的时髦字符,例如 {"(.

有谁知道如何重命名字段以便正确映射?

这是一个简短的例子,说明什么是有效的。

JSON输入:

{
    "contact_id": "",
    "status": "Partial",
    "is_test_data": "1",
    "datesubmitted": "2013-10-25 05:17:06"
}

反序列化类:

class DeserializedObject
{
    public string contact_id;
    public string status;
    public int is_test_data;
    public DateTime datesubmitted;
}

反序列化:

var deserialized = JsonConvert.DeserializeObject<DeserializedObject>(jsonInput);

这被正确映射。当我尝试处理以下字段时,问题就开始了:

{
    "contact_id": "",
    "status": "Partial",
    "is_test_data": "1",
    "datesubmitted": "2013-10-25 05:17:06",
    "[variable("STANDARD_GEOCOUNTRY")]": "Germany"
}

反序列化类:

class Output
{
    public string contact_id;
    public string status;
    public int is_test_data;
    public DateTime datesubmitted;
    public string variable_standard_geocountry; // <--- what should be this name for it to work?
}

我将不胜感激任何帮助。

4

2 回答 2

5

With JSON.NET, you'd just need to put a JsonProperty attribute on the property, like:

class Output
{
    public string contact_id;
    public string status;
    public int is_test_data;
    public DateTime datesubmitted;

    [JsonProperty("[variable(\"STANDARD_GEOCOUNTRY\")]")]
    public string variable_standard_geocountry; // <--- what should be this name for it to work?
}

This will now deserialize. This assumes that your JSON is properly formatted with those quotation marks, like:

{
    "contact_id": "",
    "status": "Partial",
    "is_test_data": "1",
    "datesubmitted": "2013-10-25 05:17:06",
    "[variable(\"STANDARD_GEOCOUNTRY\")]": "Germany"
}
于 2013-10-29T22:05:31.680 回答
2

您可以使用 JsonProperty 属性并像这样设置名称...

`

class Output
{
    public string contact_id;
    public string status;
    public int is_test_data;
    public DateTime datesubmitted;
    [JsonProperty("geocountry")]
    public string variable_standard_geocountry; // <--- what should be this name for it to work?
}

` 这里还有一个文档链接,其中可能包含您可能会发现有用的其他信息。 http://james.newtonking.com/json/help/?topic=html/JsonPropertyName.htm

于 2013-10-29T22:07:07.557 回答