7

JSON.NET を使用して、持っている JSON 応答を逆シリアル化しています。私は今まで成功してきました。JSON.NET がオブジェクトを適切に逆シリアル化するには、クラスのフィールド名を JSON とまったく同じように呼び出す必要があります。問題は、{"(.

適切にマップされるようにフィールドの名前を変更する方法を知っている人はいますか?

これが機能するものの短い例です。

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

JSON.NET を使用すると、次JsonPropertyのようにプロパティに属性を設定するだけで済みます。

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?
}

これでデシリアライズされます。これは、JSON が次のような引用符で適切にフォーマットされていることを前提としています。

{
    "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 に答える