ruijiexie
ruijiexie

Reputation: 97

Newtonsoft deserialize object

string result is below:

{ "1": "something" }

string result = "{ \"1\"' : \"somestring\"}";

public class JsonData
{
    private string _1;

    public string 1 { get { return _1; } set { _1 = value; } }

    public JsonData()
    {
    }
}

JsonData data = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonData >(result);

I want to deserialize the String but JsonData definition is wrong. Whats wrong with this?

Upvotes: 2

Views: 237

Answers (1)

Dustin Kingen
Dustin Kingen

Reputation: 21275

You code won't compile since identifiers cannot start with numbers.

You can use the JsonPropertyAttribute to reference the 1 property inside the Json.

public class JsonData
{
    [JsonProperty("1")]
    public string One { get; set; }
}

Usage:

var data = @"{ ""1"" : ""something"" }";

var result = JsonConvert.DeserializeObject<JsonData>(data);

Upvotes: 2

Related Questions