I am having issue with the below code, the following code failed to parse the given json:
import 'dart:convert';
void main() {
String jsonString = '''
{
"status": "success",
"data":{
"edit": 1,
"draft": "{"id":"25863","type":"ABC"}"
}
}
''';
try{
var decode = jsonDecode(jsonString);
print(decode);
}on FormatException catch(e){
print('error ${e.toString()}');
}
}
The error I am getting:
error FormatException: Unexpected character (at line 6, character 31)
Also I have used jsonDecode(jsonEncode(jsonString))
, but that’s does not meet my requirements as I require the data as Map<String, dynamic>. Any help is highly appreciated.
3
Answers
You have a
too much at the draft line at the end. Also you need to escape the with another if you want to use backslashes in a string definition.
But it is kind of strange that you let the "draft" field be another JSON string. It would make more sense as this and I think you should use this:
we have to change this to
"draft": "{"id":"25863","type":"ABC"}"
this"draft": {"id":"25863","type":"ABC"}
by removing this"
between json will do it. but you have to make sure your api response will be same formateYou can use like this:
}
It is better to follow architecture. So, don’t forget to create model and then use this code. Create model of the
Data
class first after then pass the json converted String to the model. with the use of model you can easily get an error message if you use wrong dataType other by default it will convert int to String as well.