Home > Software design >  When decoding json i get error Unexpected character
When decoding json i get error Unexpected character

Time:03-09

I have json file with the following data in it:

{
  "item1": "value1",
  "item2": "value2",
  "item3": "value3"
}

I also have Items() class in a seperate file which has the method getItems() method which loads the json file:

class Items {
  Future<Map<String, dynamic>> getItems() async {
    String jsonData =
        await rootBundle.loadString('assets/items.json');
    Map<String, dynamic> data = jsonDecode(jsonData);
    return data;
  }
}

I also have a scaffold to show the items with ListView.builder. I first use setState to assign the returned value of Items().getItems() to the field items. I then use the value of the field inside the LisView.builder


class ItemList extends StatefulWidget {
  const ItemList({Key? key}) : super(key: key);

  @override
  _ItemListState createState() => _ItemListState();
}

class _ItemListState extends State<ItemList> {
  late String items = '';
  setItems() async {
    final item = await Items().getItems();
    setState(() {
      items = item.toString();
    });
  }

  @override
  initState() {
    setItems();
  }

  @override
  Widget build(BuildContext context) {
    Map<String, dynamic> data = jsonDecode(items);
    debugPrint(data.toString());
    debugPrint(items);

    return Scaffold(
      body: ListView.builder(
        itemCount: data.keys.length,
        itemBuilder: (c, index) {
          return ListTile(
            title: Text("key "   data.keys.toList()[index]),
            subtitle: Text("value "   data.values.toList()[index]),
          );
        },
      ),
    );
  }
}

I am able to show the list of items when i place string hardcoded like this :

Map<String, dynamic> data = jsonDecode('{ "item1": "#48f542","item2": "value2","item3": "value3"}');

But i get an error when i use the field items like this: Map<String, dynamic> data = jsonDecode(items);

I get the error Unexpected character (at character 2) {item1: value1, item2: value2, item3: value3... ^

Both ways should work because it is basicly the same data types. I don't know what i am doing wrong.

Edit

I want to avoid using models because in my use case for example if i add another item key in the json object then i also need to change the model.

CodePudding user response:

I found the solution. The reason why i got the error is because i used jsonDecode on a bad format. The format was {item: value} instead of {"item": "value"}. So the solution was to use jsonEncode inside setState

setState(() {
      clientSettings = jsonEncode(client);});

When i did jsonEncode before jsonDecode my error was gone i can show the list of items.

CodePudding user response:

Type in the your json data format in https://app.quicktype.io/ as source type as JSON and Destination type as Dart. Then you'll get a correct model file for your JSON data. Below mentioned is an example for your given type of data

// Change your model file to this format
// To parse this JSON data, do
//
//     final saleProduct = saleProductFromJson(jsonString);

import 'dart:convert';

SaleProduct saleProductFromJson(String str) => SaleProduct.fromJson(json.decode(str));

String saleProductToJson(SaleProduct data) => json.encode(data.toJson());

class SaleProduct {
    SaleProduct({
        this.item1,
        this.item2,
        this.item3,
    });

    String item1;
    String item2;
    String item3;

    factory SaleProduct.fromJson(Map<String, dynamic> json) => SaleProduct(
        item1: json["item1"],
        item2: json["item2"],
        item3: json["item3"],
    );

    Map<String, dynamic> toJson() => {
        "item1": item1,
        "item2": item2,
        "item3": item3,
    };
}

  • Related