-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?

Matt
  • 83
  • 2
  • 9
  • 3
    Have you tried? Deserializing to a `public double price { get; set; }` property already just works, see https://dotnetfiddle.net/7bUCVL – dbc Dec 06 '19 at 05:07

2 Answers2

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.

RoadRunner
  • 25,803
  • 6
  • 42
  • 75
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; }
}
Simply Ged
  • 8,250
  • 11
  • 32
  • 40