Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize json that has some property name starting with a number

Tags:

c#

json.net

JSON data looks like this

[
    {
        "market_id": "21",
        "coin": "DarkCoin",
        "code": "DRK",
        "exchange": "BTC",
        "last_price": "0.01777975",
        "yesterday_price": "0.01770278",
        "change": "+0.43",
        "24hhigh": "0.01800280",
        "24hlow": "0.01752015",
        "24hvol": "404.202",
        "top_bid": "0.01777975",
        "top_ask": "0.01790000"
    }
]

Notice these 3 properties here 24high, 24hhlow, and 24hvol how do you make a class for that. I need all those properties by the way, not just those 3 properties I mentioned.

like image 603
jaysonragasa Avatar asked Jun 14 '14 09:06

jaysonragasa


People also ask

How do I deserialize text JSON?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is JSON property name?

The Jackson Annotation @JsonProperty is used on a property or method during serialization or deserialization of JSON. It takes an optional 'name' parameter which is useful in case the property name is different than 'key' name in JSON.

What is serialized and deserialized 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).

What is JsonProperty attribute?

JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.


2 Answers

You should use JSON.NET or similar library that offers some more advanced options of deserialization. With JSON.NET all you need is adding JsonProperty attribute and specify its custom name that appears in resulting JSON. Here is the example:

   public class MyClass
   {
        [JsonProperty(PropertyName = "24hhigh")]
        public string Highest { get; set; }
        ...

Now to deserialize:

    string jsonData = ...    
    MyClass deserializedMyClass = JsonConvert.DeserializeObject<MyClass>(jsonData);
like image 70
Borys Generalov Avatar answered Sep 22 '22 14:09

Borys Generalov


For .NET Core 3.0 and beyond, you can now use the System.Text.Json namespace. If you are using this:

public class MyClass
{
    ...
    [JsonPropertyName("24hhigh")]
    public string twentyFourhhigh { get; set; }
    ...
}

You can use JsonPropertyName Attribute.

like image 21
Pranav Avatar answered Sep 26 '22 14:09

Pranav