Home > Software engineering >  Parsing JSON String. I get Error when i try to take data in array
Parsing JSON String. I get Error when i try to take data in array

Time:01-02

This is the result from Postman

{
    "serviceResponse": {
        "data": [
            {
                "cardNo": "6375780114730832",
                "personnelNo": "47450",
                "name": null,
                "surname": null,
                "balance": 22.3,
                "walletId": 11,
                "walletName": "GIYIM KURUMSAL"
            }
        ],
        "responseMessage": "sorgulama işlemi başarılı",
        "responseCode": 0
    },
    "success": true,
    "responseCode": 0,
    "responseMessage": "sorgulama işlemi başarılı"
}

this returns me as string.

"{"serviceResponse":{"data":[{"cardNo":"6375780114730832","personnelNo":"47450","name":null,"surname":null,"balance":22.3,"walletId":11,"walletName":"GIYIM KURUMSAL"}],"responseMessage":"sorgulama işlemi başarılı","responseCode":0},"success":true,"responseCode":0,"responseMessage":"sorgulama işlemi başarılı"}"

when I try to take success, the code below works. I need balance which is in data array and the code below doesnt work. I think I should add something. What can I try?

string scs = Convert.ToString((JObject.Parse(json)["success"]));

CodePudding user response:

string balance = Convert.ToString((JObject.Parse(json)["serviceResponse"]["data"][0]["balance"]));

This will parse the JSON string and retrieve the value of the balance field from the first element of the data array.

If you want to retrieve the balance field from all elements of the data array, you can use a loop:

JArray dataArray = (JArray)JObject.Parse(json)["serviceResponse"]["data"];
foreach (JObject dataObject in dataArray)
{
    string balance = Convert.ToString(dataObject["balance"]);
    // Do something with the balance
}
  • Related