Deserializing JSON when fieldnames contain spaces

后端 未结 4 1921
野性不改
野性不改 2020-12-31 05:11

I\'m writing a tool to read JSON files. I\'m using the NewtonSoft tool to deserialize the JSOn to a C# class. Here\'s an example fragment:

 \"name\": \"Fubar         


        
相关标签:
4条回答
  • 2020-12-31 05:41

    If you want to initialize the Json manually, you can do:

    var jsonString = "{" +
                "'name': 'Fubar'," +
                "'.NET version': '4.0'," +
                "'binding type': 'HTTP'," +
                "}";
            var json = JsonConvert.DeserializeObject(jsonString);            
            return Ok(json);
    

    Don't forget to include using Newtonsoft.Json;

    0 讨论(0)
  • 2020-12-31 05:46

    Use the JsonProperty attribute to indicate the name in the JSON. e.g.

    [JsonProperty(PropertyName = "binding type")]
    public string BindingType { get; set; }
    
    0 讨论(0)
  • 2020-12-31 05:59

    Not sure why but this did not work for me. In this example I simply return a null for "BindingType" every time. I actually found it much easier to just download the Json result as a string and then do something like:

      myString = myString.Replace(@"binding type", "BindingType")
    

    You would do this as the step before deserializing.

    Also was less text by a tad. While this worked in my example there will be situations where it may not. For instance if "binding type" was not only a field name but also a piece of data, this method would change it as well as the field name which may not be desirable.

    0 讨论(0)
  • 2020-12-31 06:00

    System.Text.Json

    If you're using System.Text.Json, the equivalent attribute is JsonPropertyName:

    [JsonPropertyName(".net version")]
    public string DotNetVersion { get; set; }
    

    Example below:

    public class Data
    {
        public string Name { get; set; }
    
        [JsonPropertyName(".net version")]
        public string DotNetVersion { get; set; }
    
        [JsonPropertyName("binding type")]
        public string BindingType { get; set; }
    }
    
    // to deserialize
    var data = JsonSerializer.Deserialize<Data>(json);
    
    0 讨论(0)
提交回复
热议问题