Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Access data from JSON file & convert it to Object

Tags:

flutter

dart

I've following Json stored inside Assets/JSON/example.json

[
 {"optiontext" : "One", "optionvalue" : "One"},
 {"optiontext" : "Two", "optionvalue" : "Two"},
 {"optiontext" : "Three", "optionvalue" : "Three"}
]

I want to read JSON from this file & convert it to MyObject. Have to use it in Flutter App

like image 907
Tushar Pol Avatar asked Dec 07 '25 05:12

Tushar Pol


2 Answers

Here is sample code snippet for your case. Basically, we can use dartson package for converting.

import 'package:dartson/dartson.dart';

void main(List<String> args) {
  String jsonString = '[{"optiontext" : "One", "optionvalue" : "One"},{"optiontext" : "Two", "optionvalue" : "Two"},{"optiontext" : "Three", "optionvalue" : "Three"}]';

  var dson = new Dartson.JSON();
  List<MyObject> result = dson.decode(jsonString, new MyObject(), true);
  print(result[1].optionValue);
}

@Entity()
class MyObject {
  @Property(name:"optiontext")
  String optionText;
  @Property(name:"optionvalue")
  String optionValue;
}

As you can't use dartson in flutter due to some issue, the below code snippet can be used with the help of dart:convert

import 'dart:convert';

void main(List<String> args) {
  String jsonString = '[{"optiontext" : "One", "optionvalue" : "Value"},{"optiontext" : "Two", "optionvalue" : "Two"},{"optiontext" : "Three", "optionvalue" : "Three"}]';
  List<Map> parsedJson = JSON.decode(jsonString);
  List<MyObject> result = parsedJson.map((item) => new MyObject.fromJson(item)).toList();
  print(result[0].optionText);
  print(result[0].optionValue);
}

class MyObject {
  String optionText;
  String optionValue;

  MyObject.fromJson(Map jsonMap)
      : optionText = jsonMap['optiontext'],
        optionValue = jsonMap['optionvalue'];
}
like image 194
sayboras Avatar answered Dec 10 '25 21:12

sayboras


Here is my solution

I have the following json

[
  {
    "name": "Abhijit Sawant",
    "age": "23",
    "height":"180",
    "gender": "male",
    "hair_color": "black"
  },
  {
    "name": "Akku Sawant",
    "age": "23",
    "height":"150",
    "gender": "male",
    "hair_color": "brown"
  },
  {
    "name": "Pikki Sawant",
    "age": "23",
    "height":"120",
    "gender": "male",
    "hair_color": "grey"
  },
  {
    "name": "Chikki Sawant",
    "age": "23",
    "height":"100",
    "gender": "female",
    "hair_color": "white"
  }

]

Following is my Flutter Code

class HomePage extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return HomePageState();
  }

}

class HomePageState extends State<HomePage>{

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Loading Json"),),
      body: Container(
        child: Center(
          child: FutureBuilder(builder: (context,snapshot){
            var myData = json.decode(snapshot.data.toString());
            return new ListView.builder(
              itemCount: myData == null ? 0: myData.length,
              itemBuilder: (BuildContext context,int index){
              return Card(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    Text("Name: "+myData[index]["name"]),
                    Text("Age: "+myData[index]["age"]),
                    Text("Height: "+myData[index]["height"]),
                    Text("Gender: "+myData[index]["gender"]),
                  ],
                ),
              );
            },);
          },
          future: DefaultAssetBundle.of(context).loadString("person.json"),),

        ),
      ),
    );
  }

}
like image 26
Pritish Avatar answered Dec 10 '25 22:12

Pritish