如何命名c#类字段,以便能够用无效字符反序列化json字段名
我正在使用JSON.NET对我得到的一些JSON响应进行反序列化。 到目前为止,我一直很成功。 为了让JSON.NET正确地反序列化对象,类中的字段名需要像在JSON中一样被调用。问题是,我有一些字段的名称中有时髦的字符,我不能在C#like{“( 有人知道如何重命名字段以便正确映射吗 下面是一个简单的例子 JSON输入:如何命名c#类字段,以便能够用无效字符反序列化json字段名,c#,json.net,json-deserialization,C#,Json.net,Json Deserialization,我正在使用JSON.NET对我得到的一些JSON响应进行反序列化。 到目前为止,我一直很成功。 为了让JSON.NET正确地反序列化对象,类中的字段名需要像在JSON中一样被调用。问题是,我有一些字段的名称中有时髦的字符,我不能在C#like{“( 有人知道如何重命名字段以便正确映射吗 下面是一个简单的例子 JSON输入: { "contact_id": "", "status": "Partial", "is_test_data": "1", "datesubm
{
"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;
}
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?
}
反序列化:
var deserialized = JsonConvert.DeserializeObject<DeserializedObject>(jsonInput);
反序列化类:
class DeserializedObject
{
public string contact_id;
public string status;
public int is_test_data;
public DateTime datesubmitted;
}
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?
}
类输出
{
公共字符串联系人id;
公共字符串状态;
公共int是测试数据;
提交的公共日期时间;
公共字符串变量_standard_geoccountry;//对于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?
}
您可以使用JsonProperty属性并像这样设置名称
`
类输出
{
公共字符串联系人id;
公共字符串状态;
公共int是测试数据;
提交的公共日期时间;
[JsonProperty(“地理国家”)]
公共字符串变量_standard_geoccountry;//是否应该有反斜杠从那些引号中转出?不,它们与发布的完全相同。(我通常在所有属性上使用JSONProperty或DataMember/name。.我得到了更好看的C#和一些对更改的缓解。)@user2864740好主意。谢谢,现在我知道要查找我正在调查的主题的所有项目:)
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?
}