Dhanil Dinesan
Dhanil Dinesan

Reputation: 575

How to select value from a JSON which contains a string array?

I was trying to select a particular value from JSON data, one of its data is a string array(string[]) and after selecting this value I want to assign this value to a string[] type variable. What I already tried is passing it key-value and as a result, I will get its value.

This is the function I have written to get the data from JSON

private object[] getValueFromJSONForObject(string property, string json)
{
    JavaScriptSerializer json_serializer = new JavaScriptSerializer();
    dynamic routes_list = (dynamic)json_serializer.DeserializeObject(json);
    return routes_list[property];
}

and I'm accessing the function here

PFFilter = new string[] 
{ 
    getValueFromJSONForObject("PFFilter", savedReportsVM.BaseFilter).ToString() 
}

but I didn't get the expected result.

Here is the JSON data

{
  "DateAsOnFormated": "02-Mar-2020",
  "LookaheadDays": "90",
  "PFFilter": [
    "P",
    "F"
  ],
  "OverDueGreaterThan": "",
  "OverDueLessThan": ""
}

I'm expecting a result like this

{string[2]}

and inside this [0] "P" [1] "F"

now what I get is {string[1]} and nothing is inside the string array, How can I fix this code

Upvotes: 0

Views: 760

Answers (1)

Mohammed Sajid
Mohammed Sajid

Reputation: 4913

You can delete ToString() in

PFFilter = new string[] 
{ 
    getValueFromJSONForObject("PFFilter", savedReportsVM.BaseFilter).ToString() 
}

and replace it by the following code :

objetc[] result = getValueFromJSONForObject("PFFilter", savedReportsVM.BaseFilter);
// convert each object to string
string[] PFFilter = Array.ConvertAll(result, x => x.ToString());

i hope that will help you fix the issue

Upvotes: 1

Related Questions