如何使用字段名称的无效字符分析Json?

我从webservice收到以下JSON。 如何解析Netwtonsoft中的以下JSON?

{ "file/folder": "/Shared/Salesforce/asdf.txt" } 
   ^^^^^^^^^^
   ^^^^^^^^^^
   ^^^^^^^^^^---that is my problem

请注意,字段名称具有正斜杠,对于用作字段名称的C#无效。 (Newtownsoft会自动映射JSON名称和C#字段)

我的代码是

       JsonSerializerSettings set = new JsonSerializerSettings();
        List<UserAudit> usrs = JsonConvert.DeserializeObject<List<UserAudit>>(statusResult );

        foreach (var item in usrs)
        {
            Console.WriteLine(item.username + " " + item.ip_address);
        }

请注意,所有NewtownSoft需要的是与C#中的Javascript对象相同的名称。 它处理所有的转换。

 public class UserAudit
 {         

    public string username;
    public string filefolder;  // <----- HOW DO I SET THIS VARIABLE?  "file/folder" is invalid 
    public string transaction;
    public string access;
    public string time;

}

额外的研究

我查看了JsonConvert.DeserializeObject<List<UserAudit>>(statusResult);的重载JsonConvert.DeserializeObject<List<UserAudit>>(statusResult); 并没有看到直接的方式来重命名或重新格式化数据时,我看了JsonSerializerSettings和JsonConverters。

author: chi-coder-007
采纳答案:

您想使用JSON属性来指定要映射到模型的属性的名称。

public class UserAudit
{
    [JsonProperty("username")]
    public string UserName { get; set; }

    [JsonProperty("file/folder")]
    public string FileFolder { get; set; }

    [JsonProperty("transaction")]
    public string Transaction { get; set; }

    [JsonProperty("access")]
    public string Access { get; set; }

    [JsonProperty("time")]
    public string Time { get; set; }
}

大多数序列化器通常会查找属性以定义序列化/反序列化的方式。


参考更多解答: How do I parse Json with an invalid character for a field name? e.g. { "file/folder": "/Shared/Salesforce/asdf.txt" } with Newtonsoft? ,转载请保留出处如何使用字段名称的无效字符分析Json?及作者信息

Statement: We respect knowledge and authors. Since the content comes from the Internet and is intended for scientific research, any reprinters should retain the author's signature and origin. If you are the author of the content and feel in dispute, please contact email: 1076545519@qq.com. We will find out the situation and deal with it in time. We sincerely thank the author for his hard work.


更多:json.net