Search code examples
c#.netjsondynamicjson.net

accessing json property with given values


var orderJson = JsonConvert.DeserializeObject<dynamic>(httpResultStr);
                var orderidCount = orderJson.data.orderUuids.Count;
                for (int i = 0; i <= orderidCount; i++)
                {
                    var orderId = orderJson.data.orderUuids[i]; // my fail attempt. Didnt work
                    var map = orderJson.data.ordersMap;   
                    foreach (var d in map)
                    {
                        var receipt = d.fareInfo.totalPrice;
                        Console.WriteLine(receipt);
                    }
                 
                } 

Im trying to access the ordersMap members with the given values in orderUuids object. Inside the ordersMap Ids contain the fareInfo.totalPrice property that I'm trying to access. How would I go about achieving this?

[![json tree with ordersMap. Trying to access its members with the given values in orderUuids object.][1]][1]

enter image description here


Solution

  • You can make a partial/full map using the JSON file and use JsonConvert.DeserializeObject<>(json).

    Other solution could be create a partial map using an anonymous type. Here is a code snip.

    var anonymousTypeObject = new
    {
        status = "",
        data = new
        {
            ordersMap = new Dictionary<string, JToken>(),
            orderUuids = new string[0]
        }
    };
    var obj = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
    foreach (var kvp in obj.data.ordersMap)
    {
        var totalPrice = kvp.Value["fareInfo"]?["totalPrice"]?.ToString();
        Debug.WriteLine($"{kvp.Key} -> {totalPrice}");
    }
    

    EDIT If you don't want any map use this solution.

    var jObj = JsonConvert.DeserializeObject<JObject>(json);
    var orderUuids = jObj.SelectToken("data.orderUuids")?.Values<string>();
    foreach (var orderUuid in orderUuids)
    {
        var totalPrice = jObj.SelectToken($"data.ordersMap.{orderUuid}.fareInfo.totalPrice")?.Value<double>();
        Debug.WriteLine($"{orderUuid} -> {totalPrice}");
    }