Dart: How to convert json string without quotes to Map - json

how to convert json string without quotes to Map.
I tried below code on https://dartpad.dev/ but not working:
import 'dart:convert';
void main() async {
final String raw = "{data: {name: joy, tags: aa,bb, city: jakarta}}";
print('Test 1: $raw');
final Map<dynamic, dynamic> result = json.decode(raw);
print('Test 2: $result');
}
And this is the error for above code:
Test 1: {data: {name: joy, tags: aa,bb, city: jakarta}}
Uncaught Error: FormatException: SyntaxError: Expected property name or '}' in JSON at position 1
And I know this because my json is invalid. How to convert my json string without quotes to json string with quotes?
Actual result is:
{data: {name: joy, tags: aa,bb, city: jakarta}}
Expected result is:
{"data": {"name": "joy", "tags": "aa,bb", "city": "jakarta"}}

I fix it with below code, refer from this answer: https://stackoverflow.com/a/71025841/21092577
import 'dart:convert';
void main() async {
String raw = "{data: {name: joy, tags: aa,bb, city: jakarta}}";
print("Test 0: $raw");
String jsonString = _convertToJsonStringQuotes(raw: raw);
print("Test 1: $jsonString");
final Map<dynamic, dynamic> result = json.decode(jsonString);
print('Test 2: $result');
}
String _convertToJsonStringQuotes({required String raw}) {
String jsonString = raw;
/// add quotes to json string
jsonString = jsonString.replaceAll('{', '{"');
jsonString = jsonString.replaceAll(': ', '": "');
jsonString = jsonString.replaceAll(', ', '", "');
jsonString = jsonString.replaceAll('}', '"}');
/// remove quotes on object json string
jsonString = jsonString.replaceAll('"{"', '{"');
jsonString = jsonString.replaceAll('"}"', '"}');
/// remove quotes on array json string
jsonString = jsonString.replaceAll('"[{', '[{');
jsonString = jsonString.replaceAll('}]"', '}]');
return jsonString;
}

Your json is invalid use https://jsonlint.com/ to validate
The json should be
{
"data": {
"name": "joy",
"tags": "aa,bb",
"city": "Jakarta"
}
}
DEMO
import 'dart:convert';
void main() async {
final String raw = "{" +
" \"data\": {" +
" \"name\": \"joy\"," +
" \"tags\": \"aa,bb\"," +
" \"city\": \"Jakarta\"" +
" }" +
"}";
Map<dynamic, dynamic> resultMap = json.decode(raw);
print('Test 3: $resultMap');
}

Related

How can i convert a JSON String to List<String> in flutter?

I`m trying to retrieve the content of a table from oracle apex to my flutter app with http.get method, and atribute the values to a class i created. Problem is that 3 of the atributes of this class need to be List, so, when i try to map it, it returns this error: [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'String' is not a subtype of type 'List' in type cast.
this is the JSON:
{
"items": [
{
"id": "1",
"nome": "Feijão Tropeiro",
"id_dia_da_semana": "seg",
"id_categoria": "ga",
"url_da_imagem": "https://live.staticflickr.com/65535/52180505297_2c23a61620_q.jpg",
"ingredientes": "vários nadas"
}
],
and this is the class:
// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:convert';
class Meal {
final String id;
final String descricao;
final List<String> ingredients;
final List<String> idDiaSem;
final List<String> idCategory;
final String imageUrl;
const Meal({
required this.id,
required this.descricao,
required this.ingredients,
required this.idDiaSem,
required this.idCategory,
required this.imageUrl,
});
Map<String, dynamic> toMap() {
return <String, dynamic>{
'id': id,
'nome': descricao,
'ingredientes': ingredients,
'id_dia_da_semana': idDiaSem,
'id_categoria': idCategory,
'url_da_imagem': imageUrl,
};
}
factory Meal.fromMap(Map<String, dynamic> map) {
return Meal(
id: map['id'] as String,
descricao: map['nome'] as String,
ingredients: map['ingredientes'] as List<String>,
idDiaSem: map['id_dia_da_semana'] as List<String>,
idCategory: map['id_categoria'] as List<String>,
imageUrl: map['url_da_imagem'] as String,
);
}
String toJson() => json.encode(toMap());
factory Meal.fromJson(String source) =>
Meal.fromMap(json.decode(source) as Map<String, dynamic>);
}
can anyone help me please to fix this error? i`ve tried to convert it unsuccessfully
When you have a string you want to parse to a list, there should be a separator. For example, let's suppose this strings:
// The separator here is a comma with a space, like ', '
String str1 = 'ingredient1, ingredient2, bread, idunno, etc';
// The separator here is a simple space, ' '
String str2 = 'ingredient1 ingredient2 bread idunno etc';
Once you identified the separator in the string, you may want to use the string split method in dart, specifying the separator. For example:
// Separator is a simple comma with no spaces, ','
String str1 = 'ingredient1,ingredient2,bread,idunno,etc';
// Splits the string into array by the separator
List<String> strList = str1.split(',');
// strList = ['ingredient1', 'ingredient2', 'bread', 'idunno', 'etc'];
More information on the split dart method at https://api.dart.dev/stable/2.14.4/dart-core/String/split.html
EDIT: Example with your code, supposing the property ingredients is a string that represents an array of strings, separated with ",":
factory Meal.fromMap(Map<String, dynamic> map) {
return Meal(
id: map['id'] as String,
descricao: map['nome'] as String,
ingredients: (map['ingredientes'] as String).split(','),
// ...
You can't cast them to List<String> because they simply aren't a list. If you want them to be a List with a single element you could do this instead:
ingredients: [map['ingredientes'] as String],
idDiaSem: [map['id_dia_da_semana'] as String],
idCategory: [map['id_categoria'] as String],
or make sure the JSON has them as list like
{
"items": [
{
"id": "1",
"nome": "Feijão Tropeiro",
"id_dia_da_semana": ["seg"],
"id_categoria": ["ga"],
"url_da_imagem": "https://live.staticflickr.com/65535/52180505297_2c23a61620_q.jpg",
"ingredientes": ["vários nadas"]
}
],
try this:
static List<Meal> fromMap(Map<String, dynamic> map) {
List<Meal> result = [];
for(var item in map['items']){
result.add(Meal(
id: item['id'] as String,
descricao: item['nome'] as String,
ingredients: item['ingredientes'] as String,
idDiaSem: item['id_dia_da_semana'] as String,
idCategory: item['id_categoria'] as String,
imageUrl: item['url_da_imagem'] as String,
))
}
return result;
}

Cast Complex JSON Dart

the dart code below allows you to decode a json that comes from a backend inside resultValue, I have the response of the rest call with the json shown below, when I go to create the list with the values I have the following error, to what is due? how do i fix it?
JSON Link
Error:
//Line: return data.map((jsonObject) => new Manutenzione(
flutter: Errore: type 'List<String>'
is not a subtype of type 'String' in type cast
Dart code:
var urlmod = await Storage.leggi("URL") + "/services/rest/v3/processes/PreventiveMaint/instances";
final resultValue = await apiRequest(Uri.parse(urlmod), {}, UrlRequest.GET, true);
Map<String, dynamic> map = json.decode(resultValue);
List<dynamic> data = map["data"];
try {
return data
.map((jsonObject) => new Manutenzione(
["_id"] as String,
["_user"] as String,
["__user_description"] as String,
["Description"] as String,
["ShortDescr"] as String,
["_Site_description"] as String,
["_Team_description"] as String,
["_status_description"] as String,
["_Company_description"] as String,
))
.toList();
} catch (err) {
print("Errore: " + err.toString());
}
return List.empty();
}
JSON:
{
...
data: [
{
_id: value1,
_user: value2,
..
},
{
_id: value1,
_user: value2,
..
},
]
}
You forgot to specify jsonObject before the square brackets.
var urlmod = await Storage.leggi("URL") + "/services/rest/v3/processes/PreventiveMaint/instances";
final resultValue = await apiRequest(Uri.parse(urlmod), {}, UrlRequest.GET, true);
Map<String, dynamic> map = json.decode(resultValue);
List<dynamic> data = map["data"];
try {
return data
.map((jsonObject) => new Manutenzione(
jsonObject["_id"] as String,
jsonObject["_user"] as String,
jsonObject["__user_description"] as String,
jsonObject["Description"] as String,
jsonObject["ShortDescr"] as String,
jsonObject["_Site_description"] as String,
jsonObject["_Team_description"] as String,
jsonObject["_status_description"] as String,
jsonObject["_Company_description"] as String,
))
.toList();
} catch (err) {
print("Errore: " + err.toString());
}
return List.empty();
}

Dart convert string without quotes to json

I am trying to convert a string to json string.
String I get:
String myJSON = '{codigo: 1050, decricao: Mage x, qntd: 1, tipo: UN, vUnit: 10,9, vTotal: 10,90}';
String I need:
String myJSON = '{"codigo": "1050", "decricao": "Mage x", "qntd": "1", "tipo": "UN", "vUnit": "10,9", "vTotal": "10,90"}';
Could someone shed some light on how I can add the quotes?
You can easily convert a String using replaceAll.
Code:
String myJSON = '{codigo: 1050, decricao: Mage x, qntd: 1, tipo: UN, vUnit: 10,9, vTotal: 10,90}';
myJSON = myJSON.replaceAll('{', '{"');
myJSON = myJSON.replaceAll(': ', '": "');
myJSON = myJSON.replaceAll(', ', '", "');
myJSON = myJSON.replaceAll('}', '"}');
print(myJSON);
Output:
{"codigo": "1050", "decricao": "Mage x", "qntd": "1", "tipo": "UN", "vUnit": "10,9", "vTotal": "10,90"}
Convert using json encode
import 'dart:convert';
const JsonEncoder encoder = JsonEncoder.withIndent(' ');
String myJSON = '{codigo: 1050, decricao: Mage x, qntd: 1, tipo: UN, vUnit: 10,9, vTotal: 10,90}';
String str = encoder.convert(myJSON);

Rest Assured - compare json response with local json file

I have a local json file test.json
[
{
"id": 1,
"title": "test1"
},
{
"id": 2,
"title": "test2"
}
]
Class to read the json file
public static String getFileContent(String fileName){
String fileContent = "";
String filePath = "filePath";
try {
fileContent = new String(Files.readAllBytes(Paths.get(filePath)));
return fileContent;
}catch(Exception ex){
ex.printStackTrace();
}finally{
return fileContent;
}
}
I use rest assured to make the request and get same json response back
String fileContent= FileUtils.getFileContent("test.json");
when().
get("/testurl").
then().
body("", equalTo(fileContent));
This is what I got from local file
[\r\n {\r\n \"id\": 1,\r\n \"title\": \"test1\"\r\n },\r\n {\r\n \"id\": 2,\r\n \"title\": \"test2\"\r\n }\r\n]
This is the actual response:
[{id=1, title=test1}, {id=2, title=test2}]
Is there any better way to compare those two? I try to do something like fileContent.replaceAll("\\r\\n| |\"", ""); but it just removed all the space [{id:1,title:test1},{id:2,title:test2}]
Any help? Or any ways that just compare the content and ignore newline, space and double quote?
You can use any of the following methods
JsonPath :
String fileContent = FileUtils.getFileContent("test.json");
JsonPath expectedJson = new JsonPath(fileContent);
given().when().get("/testurl").then().body("", equalTo(expectedJson.getList("")));
Jackson :
String fileContent = FileUtils.getFileContent("test.json");
String def = given().when().get("/testurl").then().extract().asString();
ObjectMapper mapper = new ObjectMapper();
JsonNode expected = mapper.readTree(fileContent);
JsonNode actual = mapper.readTree(def);
Assert.assertEquals(actual,expected);
GSON :
String fileContent = FileUtils.getFileContent("test.json");
String def = given().when().get("/testurl").then().extract().asString();
JsonParser parser = new JsonParser();
JsonElement expected = parser.parse(fileContent);
JsonElement actual = parser.parse(def);
Assert.assertEquals(actual,expected);

how to stringify json in flutter

In flutter(dart), it is easy to deserialize Json and get a token from it, but when I try to serialize it again, the quotation marks around the keys and values with disappear.
String myJSON = '{"name":{"first":"foo","last":"bar"}, "age":31, "city":"New York"}';
var json = JSON.jsonDecode(myJSON); //_InternalLinkedHashMap
var nameJson = json['name']; //_InternalLinkedHashMap
String nameString = nameJson.toString();
Although the nameJson have all the double quotations, the nameString is
{first: foo, last: bar}
(true answer is {"first": "foo", "last": "bar"})
how to preserve Dart to remove the "s?
When encoding the object back into JSON, you're using .toString(), which does not convert an object to valid JSON. Using jsonEncode fixes the issue.
import 'dart:convert';
void main() {
String myJSON = '{"name":{"first":"foo","last":"bar"}, "age":31, "city":"New York"}';
var json = jsonDecode(myJSON);
var nameJson = json['name'];
String nameString = jsonEncode(nameJson); // jsonEncode != .toString()
print(nameString); // outputs {"first":"foo","last":"bar"}
}