S
S
Stas Korostelev2015-09-23 23:25:30
Programming
Stas Korostelev, 2015-09-23 23:25:30

Good night everyone, can you help me with JSON in C#?

string json = @"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99
"; there is such a json (I copied it somewhere on the Internet) how can I get Name and Price out of it, for example? PS using Newtonsoft.Json library
Thanks )

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mpavlov, 2015-09-28
@ZorG761

First, as noted above, check the JSON for validity. If everything is ok, choose any of the options below.
Write a class with the fields Name, Expiry, Price, and then build it with Newtonsoft. It will look something like this:

public class MyClass
{
    public string Name {get;set;}
    public string Expiry {get;set;}
    public string Price {get;set;}
}

public class Parser
{
    public void Process(string json)
    {
        var result = JObject.Parse(json).ToObject<MyClass>();

        var name = result.Name;
        var expiry = result.Expiry;
        var price = result.Price;
    }
}

There is a less beautiful, but working version without creating a class:
public class Parser
{
    public void Process(string json)
    {
        var result = JObject.Parse(json);

        var name = result["Name"];
        var expiry = result["Expiry"];
        var price = result["Price"];
    }
}

In the latter case, it will be necessary to cast the value types to the required ones.

L
littleguga, 2015-09-24
@littleguga

As GavriKos correctly noted , your json is not valid

{
"Name": "Apple",
"Expiry": 1230422400000,
"Price": 3.99
}

Here is a valid example.
json["name"] - displays what you need

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question