Sasha Korkin
Sasha Korkin

Reputation: 93

How to convert inner json part into object in dart/flutter

I need to convert every element of 'content' array to object.

Here is json:

{
  "content": [
    {
      "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "author": {
        "userId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      },
      "createDate": "2020-01-30T20:18:29.764Z",
      "executor": {
        "userId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      },
    }
  ],
  "first": true,
  "numberOfElements": 0,
}

The problem is that 'content' array is inside json, and its parts as executor and author has to be objects too, and I don't know how to reach it and parse. How it can be done? Any help, thanks.

Upvotes: 0

Views: 92

Answers (1)

Richard Heap
Richard Heap

Reputation: 51750

You access the elements like this:

  var decoded = json.decode(j);
  var inner = decoded['content'][0]; // if you expect more than one entry, iterate the list
  print(inner['id']); // -> 3fa85f64-5717-4562-b3fc-2c963f66afa6
  print(inner['createDate']);
  print(inner['author'].runtimeType); // another Map<String, dynamic> as expected
  print(inner['author']['userId']);

You can create Dart classes to model, for example, a 'user' if you want.

Upvotes: 1

Related Questions