-1

I have this JSON:

{ "price": "0.002200" } 

I'd like to deserialize price to double, but it is a string.

How can I do?

1
  • 3
    Have you tried? Deserializing to a public double price { get; set; } property already just works, see dotnetfiddle.net/7bUCVL Commented Dec 6, 2019 at 5:07

2 Answers 2

2

You would just create a class to map the JSON:

public class RootObject { public double price { get; set; } } 

Then just deserialize with JsonConvert.DeserializeObject:

JsonConvert.DeserializeObject<RootObject>(json) 

Full Program:

using Newtonsoft.Json; public class RootObject { public double price { get; set; } } public class Program { public static void Main() { var json = @"{""price"": ""0.002200""}"; var root = JsonConvert.DeserializeObject<RootObject>(json); Console.WriteLine(root.price); // 0.0022 } } 

Note: This assumes you have the Newtonsoft.Json NuGet package installed.

Sign up to request clarification or add additional context in comments.

Comments

2

One option is to create class that represents the JSON and deserialize into that class:

class Program { static void Main(string[] args) { var json = "{ \"price\": \"0.002200\" }"; var data = JsonConvert.DeserializeObject<Data>(json); Console.WriteLine(data.Price); } } class Data { public double Price { get; set; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.