Deserializing JSON when fieldnames contain spaces

浪子不回头ぞ 提交于 2019-12-19 06:03:32

问题


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",
 ".NET version": "4.0",
 "binding type": "HTTP",

The field names contain spaces and other characters (the .) that are invalid in C# identifiers. What is the correct way to do this?

(Unfortunately I don't have the option of changing the JSON format.)


回答1:


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

[JsonProperty(PropertyName = "binding type")]
public string BindingType { get; set; }



回答2:


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.




回答3:


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;




回答4:


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


来源:https://stackoverflow.com/questions/23183238/deserializing-json-when-fieldnames-contain-spaces

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