2

I have a JSON file with different and unique objects as Employee1, employee2 and so on. Now I want to read the JSON file using the unique objects and then map the object contents to a variable and use it in my project.

the JSON file is as follows:

[
    {
        "employee1": {
            "firstName": "Lokesh",
            "lastName": "Gupta",
            "website": "howtodoinjava.com"
        }
    },
    {
        "employee2": {
            "firstName": "Brian",
            "lastName": "Schultz",
            "website": "example.com"
        }
    }
]

3 Answers 3

2

feed the above json list to json.decode()

var dJson = json.decode(list);
//which results in dJson being a List<dynamic>
//access the first result
var first = dJson[0];
//which gives you a Map because the json.decode maintains the structure of the json given
var employee1 = first["employee1"];
//will give you another Map
var firstName = employee1["firstName"];
//will give you the firstName
print(firstName);//Lokesh
Sign up to request clarification or add additional context in comments.

4 Comments

then for accessing employee2 I would have to increment dJson[1] and then follow the same steps as you have done for employee1 right?
Worked as expected as you explained in the code. And Really sorry for the late reply.
Is there a way I can search for employee1 in the same JSON file then map that to a variable
Did the job, modified the JSON Syntax to match the Map syntax and solved my part thanks for the help
2

Just check out this example that I have created: Following is the json that you provided.

[
    {
        "employee1": {
            "firstName": "Lokesh",
            "lastName": "Gupta",
            "website": "howtodoinjava.com"
        }
    },
    {
        "employee2": {
            "firstName": "Brian",
            "lastName": "Schultz",
            "website": "example.com"
        }
    }
]

This is the solution :

import 'dart:convert';

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: HomePage());
  }
}

class Employee {
  String firstName;
  String lastName;
  String website;

  Employee({this.firstName, this.lastName, this.website});
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool _isLoading = false;

  List<Employee> employeeList = List();

  @override
  void initState() {
    super.initState();
    getData();
  }

  getData() async {
    String data =
        await DefaultAssetBundle.of(context).loadString("json/parse.json");

    var jsonData = json.decode(data);

    jsonData.forEach((item) {
      item.forEach((key, value) {
        employeeList.add(Employee(
            firstName: value['firstName'],
            lastName: value['lastName'],
            website: value['website']));
      });
    });

    print(employeeList.length);

    employeeList.forEach((item) {
      print(item.firstName);
      print(item.lastName);
      print(item.website);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: Text(''));
  }
}

Let me know if it works.

Comments

0

First, try to create a model out of the JSON you are getting. For the sample provide the Model, would look like this.

class EmployeeModel {
  Employee1 employee1;

  EmployeeModel({this.employee1});

  EmployeeModel.fromJson(Map<String, dynamic> json) {
    employee1 = json['employee1'] != null
        ? new Employee1.fromJson(json['employee1'])
        : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.employee1 != null) {
      data['employee1'] = this.employee1.toJson();
    }
    return data;
  }
}

class Employee1 {
  String firstName;
  String lastName;
  String website;

  Employee1({this.firstName, this.lastName, this.website});

  Employee1.fromJson(Map<String, dynamic> json) {
    firstName = json['firstName'];
    lastName = json['lastName'];
    website = json['website'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['firstName'] = this.firstName;
    data['lastName'] = this.lastName;
    data['website'] = this.website;
    return data;
  }
}

Then use

EmployeeModel employee = EmployeeModel.fromJson(responseJSON);

to access the values within the model.

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.