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);
Related
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');
}
I'm trying to fetch some data from json. I made function to fetch JSON.
My code:
val obj = JSONObject(getJSONFromAssets()!!)
val userArray = obj.getJSONObject("user_id")
My code to fetchAssets:
private fun getJSONFromAssets(): String ?{
var json: String? = null
val charset: Charset = Charsets.UTF_8
try{
val jsonFile = assets.open(K.json.jsonFileName)
val size = jsonFile.available()
val buffer = ByteArray(size)
jsonFile.read(buffer)
jsonFile.close()
json = String(buffer, charset)
}
catch (ex: IOException){
ex.printStackTrace()
return null
}
return json
}
JSON File:
{
"user_id": "1",
"acounts": [
{
"id": "1",
"AccountNumber": "HR123456789012345678901",
"amount": "2.523,00",
"currency": "USD",
"transactions":
UserModelClass:
data class UserModelClass (
val user_id:String,
val accounts: List<AccountsList>
)
Problem is that I have user ID and then accounts where I can loop easy.
Error: Failed to open file, no such file or directory.
Value 1 at user_id of type java.lang.String cannot be converted to JSONObject
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);
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"}
}
Is there a straight forward way to format a JSON string in scala?
I have a JSON String like this:
val json = {"foo": {"bar": {"baz": T}}}
Can I use a function f such that:
f(json) = {
"foo":
{"bar":
{"baz": T}
}
}
I know the formatting I have done in my answer is no perfect, but you get the point. And yes, can it be done without using Play Framework?
In case you are using Play Framework you could use Json.prettyPrint method to format JsValue:
import play.api.libs.json.Json
val str = """{"foo": {"bar": {"baz": "T"}}}"""
val jsValue = Json parse str
// JsValue = {"foo":{"bar":{"baz":"T"}}}
Json prettyPrint jsValue
// String =
// {
// "foo" : {
// "bar" : {
// "baz" : "T"
// }
// }
// }
In case you are using scala.util.parsing.json you have to create such method by yourself. For instance:
def format(t: Any, i: Int = 0): String = t match {
case o: JSONObject =>
o.obj.map{ case (k, v) =>
" "*(i+1) + JSONFormat.defaultFormatter(k) + ": " + format(v, i+1)
}.mkString("{\n", ",\n", "\n" + " "*i + "}")
case a: JSONArray =>
a.list.map{
e => " "*(i+1) + format(e, i+1)
}.mkString("[\n", ",\n", "\n" + " "*i + "]")
case _ => JSONFormat defaultFormatter t
}
val jsn = JSON.parseRaw("""{"foo": {"bar": {"baz": "T"}, "arr": [1, 2, "x"]}, "foo2": "a"}""").get
// JSONType = {"foo" : {"bar" : {"baz" : "T"}, "arr" : [1.0, 2.0, "x"]}, "foo2" : "a"}
format(jsn)
// String =
// {
// "foo": {
// "bar": {
// "baz": "T"
// },
// "arr": [
// 1.0,
// 2.0,
// "x"
// ]
// },
// "foo2": "a"
// }
Note that this is not an efficient implementation.
I thought I read somewhere that Typesafe was considering separating their JSON processing out of Play, so look into that to apply #senia's solution first.
Otherwise, look at Jackson--or more precisely, the Scala wrapper for Jackson:
val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)
val writer = mapper.writerWithDefaultPrettyPrinter
val json = writer.writeValueAsString(Object value)
I've also heard that the kids are really into Scala Pickling, which apparently has pretty printing as well.