-2

I have a json object like that:

enter image description here

And i want to access the "question" field throught this code-line:

string msg = (json1["data"][0]["question"]).ToString();

But it doesnt work, why?

  • 2
    "data" isn't an array. You can tell that because it's an object (declared using `{ }`) and not an array (declared using `[ ]`). – ProgrammingLlama Jun 23 '20 at 06:48
  • @John yea, thats the problem, sorry ;( – Logo Portman Jun 23 '20 at 06:51
  • Does this answer your question? [How to handle both a single item and an array for the same property using JSON.net](https://stackoverflow.com/questions/18994685/how-to-handle-both-a-single-item-and-an-array-for-the-same-property-using-json-n) – Drag and Drop Jun 23 '20 at 07:05
  • Imo, we have a little XY here. While the issue at hand is that `data` is not an Array. Your real problems came from "data" being either an object or an array. I will create a class where data is an array. And deserialize it to an array of one element when it's a single object. That way you could process Data like a collection no matter what. Using Drag and Drop 's link for that. – xdtTransform Jun 23 '20 at 07:13

2 Answers2

1

But it doesnt work, why?

Because you need to look at the json again.

"data" is an object, not an array. As such "[0]" is not valid as it would access the first element of the array. The only array you have in there is the "answers" element. "question" is directly a property of "data".

TomTom
  • 61,059
  • 10
  • 88
  • 148
-1

Prepare a C# Model like below

public class rootClass
    {
        public bool ok { get; set; }
        public data data { get; set; }
    }

    public class data
    {
        public string question { get; set; }
        public string[] answers { get; set; }
        public int id { get; set; }
    }

and use JsonConvert(Newtonsoft dll) class to deserialise and access like below

rootClass rootClass = JsonConvert.DeserializeObject<rootClass>(inputJson);
            string msg = rootClass.data.question;
surya teja
  • 20
  • 8