-3

I have a JSON string like this :

{
    "message": "Login successful",
    "result": [
        {
            "_id": "60ed65f6cb33920004c3117a",
            "username": "ajay",
        }
    ]
}

I Convert above string in jsondecode(response.body) format using flutter I got below string

    {
       message: Login successful, 
       result:[
          { 
             _id: 60ed65f6cb33920004c3117a,
             username: ajay
          }
       ]
   }

I Can find _id and username of result section when user logged in successfully

1

2 Answers 2

3

You can use string indexes to access these properties:

print(object['result'][0]['_id']);        // 60ed65f6cb33920004c3117a
print(object['result'][0]['username']);   // ajay

Now this is not ideal, and if you have many such objects it's probably worth it to use a model class and serialize your JSON into that, as highlighted in the Flutter documentation:

https://flutter.dev/docs/development/data-and-backend/json#serializing-json-inside-model-classes

The documentation also refers to the cookbook for a more complete and comprehensive example of using such model classes:

https://flutter.dev/docs/cookbook/networking/background-parsing

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

Comments

1

Try to use the following code snippet, you will get your results on var id and username:

var id;
var username;

var resp = jsonDecode(response.body);

id = resp['result'][0]['_id'];
username = resp['result'][0]['username'];

Comments

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.