How do I parse Json with an invalid character for a field name? e.g. { “file/folder”: “/Shared/Salesforce/asdf.txt” } with Newtonsoft?

独自空忆成欢 提交于 2019-12-11 12:22:42

问题


I received the following JSON from a webservice. How do I parse the following JSON in Netwtonsoft?

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

Note that the field name has a forward slash, which is invalid for C# when used as a field name. (Newtownsoft does automatic mappings between JSON names and C# fields)

The code I have is

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

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

Note how all NewtownSoft needs is the same name for the Javascript object in C#. It handles all the conversion.

 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;

}

Additional research

I looked at the overload for JsonConvert.DeserializeObject<List<UserAudit>>(statusResult); and didn't see a direct way to rename or reformat the data when it comes in. I looked at both JsonSerializerSettings, and JsonConverters.


回答1:


You want to use JSON attributes to specify the name of the property to map to the model.

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

It's common with most serializers to look for attributes to define how they should serialize/deserialize.




回答2:


Change it from this.

    "/Shared/Salesforce/asdf.txt"

to this

    @"/Shared/Salesforce/asdf.txt"


来源:https://stackoverflow.com/questions/19865260/how-do-i-parse-json-with-an-invalid-character-for-a-field-name-e-g-file-fol

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!