我有以下json,正在填充:
new Gson().toJson(batch.getProducts());
但是当我将它添加到我的主JSONObject时,它是json的值正在执行所有json(甚至是键)的事实被转义。
{"name":"Ufud","store":2,"products":"[{\"name\":\"Test2\",\"stock\":2,\"value\":19.9},{\"name\":\"Test2\",\"stock\":2,\"value\":19.9},{\"name\":\"Teste2\",\"stock\":2,\"value\":19.9}]"}
有什么方法可以防止这种情况吗?
答案 0 :(得分:0)
如果您将来要操纵json,可以考虑将其转换为字符串,而不是转换为可以很容易地添加到现有JsonObject的JsonElement
JsonObject mainObject = getMainObject(); //method which creates your main object. You can change it to variable reference
JsonElement productsElement = new Gson().toJsonTree(batch.getProducts()); //converting your object into JsonElement
mainObject.add("products", productsElement); //insering products element into object.
String json = new Gson().toJson(mainObject); //converting object with products element into a json string