flutter convert json string to json
To convert a JSON string to a JSON object in Flutter, you can make use of the jsonDecode()
method provided by the dart:convert
library. Here's an example:
import 'dart:convert';
void main() {
String jsonString = '{"name": "John", "age": 30, "city": "New York"}';
// Convert JSON string to JSON object
Map<String, dynamic> jsonObject = jsonDecode(jsonString);
// Access values from JSON object
String name = jsonObject['name'];
int age = jsonObject['age'];
String city = jsonObject['city'];
// Print the values
print('Name: $name');
print('Age: $age');
print('City: $city');
}
In the above example, we have a JSON string jsonString
that represents an object with three properties: "name", "age", and "city". We use the jsonDecode()
method to convert this string into a JSON object of type Map<String, dynamic>
. We can then access the values from the JSON object using the corresponding keys.
The output of the above code will be:
Name: John
Age: 30
City: New York
This demonstrates how to convert a JSON string to a JSON object in Flutter using the jsonDecode()
method. Remember to import the dart:convert
library to use the jsonDecode()
function.