0

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

9
  • getValueFromJSONForObject("PFFilter", savedReportsVM.BaseFilter).ToString() just returns a single string. Why are you expecting two? Commented Mar 4, 2020 at 14:36
  • But here I didn't get even the single value. How can I modify the code to get proper result. Commented Mar 4, 2020 at 14:38
  • Are you doing this on a web server? Normally I'd use JSON.net for this. Interestingly, the first sentence of the documentation says precisely this. Commented Mar 4, 2020 at 14:44
  • @RobertHarvey I'm doing this in the controller, and it works fine with other data, the return type was String and I modify this with object[] when I get an error with that function return type Commented Mar 4, 2020 at 14:48
  • Are you sure your json string is as you have it, because your code works as is for me. Commented Mar 4, 2020 at 15:04

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Ok let me try with this one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.