Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing JSON when fieldnames contain spaces

Tags:

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

like image 315
Sisiutl Avatar asked Apr 20 '14 13:04

Sisiutl


People also ask

Can JSON field names have spaces?

Whitespace (Space, Horizontal tab, Line feed or New line or Carriage return) does not matter in JSON. It can also be minified with no affect to the data. Object literal names MUST be lowercase (ie – null, false, true etc). Keep all name and value pairs in quotes to aviod.

What is serializing in JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

Does JSON serialize data?

JSON is a format that encodes an object to a string. On the transmission of data or storing is a file, data need to be in byte strings, but as complex objects are in JSON format. Serialization converts these objects into byte strings which is JSON serialization.

What does JObject parse do?

The method JObject. Parse() is a JObject class method. This parse method is used to parse a JSON string into a C# object. It parses the data of string based on its key value.


1 Answers

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

[JsonProperty(PropertyName = "binding type")]
public string BindingType { get; set; }
like image 174
Craig W. Avatar answered Oct 30 '22 02:10

Craig W.