Héctor León
Héctor León

Reputation: 31

Query a JSON using LINQ

I have this JSON:

{   
   "fuel_distance": 461.6,
   "fuel_distance_um": "MI",
   "id": "62157",
   "stops": [
       {            
           "id": "zz1dnvtir8j050oW100204",            
           "latitude": 34.0214
       }
    ]
}

and I would like to get the values in the picture.

Visualization:

I'm working on a C# project. I would like to get those using LINQ.

Thank you very much in advance guys!

Upvotes: 0

Views: 275

Answers (2)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14228

Demo on dotnet fiddle

You can use Newtonsoft to DeserializeObject then get values as you wish like below.

public class Program
{
    public static void Main()
    {
        var json = "{\"fuel_distance\": 461.6, \"fuel_distance_um\": \"MI\", \"id\": \"62157\", \"stops\": [{ \"id\": \"zz1dnvtir8j050oW100204\", \"latitude\": 34.0214 }]}";
        var deserializedObject = JsonConvert.DeserializeObject<MyModel>(json);
        Console.WriteLine("Id: " + deserializedObject.id);

        var stopIds = deserializedObject.stops.Select(p => p.id);
        foreach(var id in stopIds)
          Console.WriteLine("Id child: "+ id);
        }
}

public class MyModel 
{
    public decimal fuel_distance {get; set;}
    public string fuel_distance_um {get; set;}
    public string id {get; set;}
    public MyChildModel[] stops {get; set;}
}

public class MyChildModel 
{
    public string id {get; set;}
    public decimal latitude {get; set;}
}

Output

Id: 62157
Id child: zz1dnvtir8j050oW100204

Updated

You can also get the result like below

    var result = new
    { 
        ID = deserializedObject.id, 
        stopId = deserializedObject.stops[0].id
    };

Upvotes: 1

Matt
Matt

Reputation: 27001

Using newtonsoft - also I'm assuming you want a collection of stop ids, not just the one id -

void Main()
{
    var json = "{'fuel_dist': 123, 'fuel_dist_um':'MI', 'id': '62157', 'stops': [{ 'id': 'zz1', latitude: 34.0214}]}";
    JObject jo = JObject.Parse(json);
    var id = (string)jo["id"];
    var arr = jo["stops"] as JArray;
    var stopIds = arr.Select(x=>(string)x["id"]);
    // alternative if it's just one
   var stopId = arr.FirstOrDefault(x=>(string)x["id"]);
}

Upvotes: 1

Related Questions