How to convert a JSON string to a dynamic object dart Flutter



In Dart and Flutter, JSON (JavaScript Object Notation) is a commonly used data interchange format for transmitting and storing data. When working with JSON, you may encounter situations where you need to convert a JSON string to a dynamic object. This can be useful for accessing properties within the JSON data without having to create a custom class.

Convert a JSON string to a dynamic object in Flutter

Here are the steps to convert a JSON string to a dynamic object in Dart Flutter:

Step 1: Import the dart:convert library

In order to convert the JSON string to a dynamic object, you need to import the dart:convert library. This library provides several functions for working with JSON data, including the ability to encode and decode JSON.

import 'dart:convert';

Step 2: Create a JSON string

In order to demonstrate how to convert a JSON string to a dynamic object, you need to first create a JSON string. You can do this by using the jsonEncode() function provided by the dart:convert library.

String jsonString = '{"name": "Jony", "age": 20, "vill": "New York"}';

Step 3: Convert the JSON string to a dynamic object

Once you have a JSON string, you can use the jsonDecode() function provided by the dart:convert library to convert it to a dynamic object. This function takes a String as its input and returns a dynamic object.

dynamic json = jsonDecode(jsonString);

Step 4: Access the properties of the dynamic object

Once you have a dynamic object, you can access its properties using the dot notation or the square bracket notation.

String name = json['name'];
int age = json['age'];
String city = json['vill'];

Note that when you access properties using the square bracket notation, the key must be a String. If you try to access a property using an integer or any other type, you will get a runtime error.

Flutter string to JSON

Certainly! Here’s an example of how you can convert a Flutter string to JSON format:

import 'dart:convert';

void main() {
  String jsonString = '{"name":"John","age":30,"city":"New York"}';
  
  // Convert string to JSON
  Map<String, dynamic> json = jsonDecode(jsonString);
  
  // Access values from JSON
  String name = json['name'];
  int age = json['age'];
  String city = json['city'];
  
  // Print values
  print('Name: $name');
  print('Age: $age');
  print('City: $city');
}

In the example above, we use the jsonDecode function from the dart: convert library to convert the string jsonString into a JSON object. We can then access the values in the JSON object using the corresponding keys.

Make sure to import the dart: convert library at the beginning of your Dart file in order to use the jsonDecode function.

JSON to dart

To convert JSON to Dart objects, you can use the json_serializable package in Dart. This package helps generate Dart code for converting between JSON and Dart objects automatically. Here’s an example of how to use it:

First, make sure you have the json_serializable package added as a dependency in your pubspec.yaml file:

dependencies:
  json_annotation: ^4.0.1
  json_serializable: ^4.1.3

Next, create a Dart file (e.g., example.dart) and import the necessary packages:

import 'dart:convert';
import 'package:json_annotation/json_annotation.dart';

part 'example.g.dart'; // This is the generated code file

@JsonSerializable() // Add this annotation to your class
class Example {
  final String name;
  final int age;

  Example({required this.name, required this.age});

  // Add this factory method to create an instance from a JSON map
  factory Example.fromJson(Map<String, dynamic> json) =>
      _$ExampleFromJson(json);

  // Add this method to convert the instance to a JSON map
  Map<String, dynamic> toJson() => _$ExampleToJson(this);
}

void main() {
  // Example usage:
  String jsonStr = '{"name": "John Doe", "age": 30}';
  Map<String, dynamic> jsonMap = json.decode(jsonStr);

  Example example = Example.fromJson(jsonMap);
  print(example.name); // Output: John Doe
  print(example.age); // Output: 30

  Map<String, dynamic> convertedJson = example.toJson();
  String convertedJsonStr = json.encode(convertedJson);
  print(convertedJsonStr); // Output: {"name": "John Doe", "age": 30}
}

Run the Dart code, and it will deserialize the JSON into a Dart object using the Example.fromJson factory method. You can then access the properties of the object as usual. To convert the object back to JSON, call the toJson method, which returns a JSON map. Finally, you can use json.encode to convert the map back to a JSON string.

Before running the code, make sure to generate the necessary serialization code by running the following command in the terminal:

flutter pub run build_runner build

This command generates the corresponding serialization code for your class and creates a example.g.dart file. The generated code handles the conversion between JSON and Dart objects.

That’s it! You now have a basic example of converting JSON to Dart objects using the json_serializable package. Remember to adjust the class and property names according to your JSON structure.

Read also, How to Get data a Nested JSON Object in Flutter?

Conclusion

In conclusion, converting a JSON string to a dynamic object in Dart and Flutter is a straightforward process. By following these simple steps, you can easily access properties within a JSON object without having to create a custom class.

Leave a Comment