i have here a little project that getting data from a table and return it as json with the use of json, but the json its returning seems to be a string. it has back slash, can someone knows what it causes.
Result result = new Result();
result.responseCode = "00";
result.responseMessage = "Successful";
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.serializeNulls().create();
String x = "x";
String name="",address ="",msisdn="",email="";
Details details = new Details();
for(DataRow dr : drw_){
name = dr.get("NAME").toString();
details.name = name;
address = dr.get("ADDRESS").toString();
details.address = address;
msisdn = dr.get("CONTACTNUMBER").toString();
details.msisdn = msisdn;
email = dr.get("EMAIL").toString();
details.email = email;
gson.toJson(details);
result.detailsList.add(gson.toJson(details));
}
System.out.println(gson.toJson(details));
System.out.println(gson.toJson(result));
Sample output:
{"responseMessage":"Successful",
"responseCode":"00",
"detailsList":["{\"name\":\"name1\",
\"address\":\"address st 1\",
\"msisdn\":\"09211231234\",
\"email\":\"email#someweb.com\"}"
,"{
\"name\":\"testname\",
\"address\":\"testadress st 1 CITY\",
\"msisdn\":\"+639171234567\",
\"email\":\"myemail#someweb.com\"}
"]
}
Expected Output:
{"responseMessage":"Successful",
"responseCode":"00",
"detailsList":[{"name":"name1",
"address":"address st 1",
"msisdn":"09211231234",
"email":"email#someweb.com"}
,{
"name":"testname",
"address":"testadress st 1 CITY",
"msisdn":"+639171234567",
"email":"myemail#someweb.com"}
]}
The Slashes are escape because of the " value. This can break a string. For example
String x = "{"name":"name1"}" // Not a valid string
String x = "{\"name\":\"name1\"}" // Valid string
Try it out and the compiler will show you the errors.
You are converting it to gson twice.. So the second parsing escapes the double quotes. Try like this
Result result = new Result();
result.responseCode = "00";
result.responseMessage = "Successful";
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.serializeNulls().create();
String x = "x";
String name="",address ="",msisdn="",email="";
Details details = new Details();
for(DataRow dr : drw_){
name = dr.get("NAME").toString();
details.name = name;
address = dr.get("ADDRESS").toString();
details.address = address;
msisdn = dr.get("CONTACTNUMBER").toString();
details.msisdn = msisdn;
email = dr.get("EMAIL").toString();
details.email = email;
result.detailsList.add(details);
}
System.out.println(gson.toJson(details));
System.out.println(gson.toJson(result));
Did you try: result.detailsList.add(details);? You should let JSON serialize everything in one go and not put a JSON String inside another object.
You are building a json where each element of detailList list field is an string containing the string representation of other Json previously generated:
result.detailsList.add(gson.toJson(details));
Your detailsList seems to be a list of strings.
detailsList should be a collection of a class Details objects instead of Strings.
This way, the line above should be changed to:
result.detailsList.add(details);
Otherwise, which is happening to you now, you are encoding strings containing quotes thus, these quotes are being encoding with escape characters.
Related
I have a Java POJO
public class TagBean {
private String type;
private String id;
public TagBean(String type, String id) {
this.type = type;
this.id = id;
}
// getters
// setters
}
I'm building pojo's and adding them to a List, as
....
List<TagBean> channelsList = new ArrayList<>();
List<TagBean> showsList = new ArrayList<>();
for each <business logic> {
if value=channels {
channelsList.add(new TagBean(...));
}
if value=shows {
showsList.add(new TagBean(...));
}
}
Gson gson = new GsonBuilder().create();
JsonObject tjsonObject = new JsonObject();
tjsonObject.addProperty("channels", gson.toJson(channelsList));
tjsonObject.addProperty("shows", gson.toJson(showsList));
JsonObject mainjsonObject = mainjsonObject.add("tags", tjsonObject);
return mainjsonObject;
My output is:
{
"tags": {
"channels": "[{\"type\":\"channel\",\"id\":\"channel\",\"name\":\"Channel\",\"parent\":\"SXM\"}]",
"shows": "[{\"type\":\"shows\",\"id\":\"shows\",\"name\":\"Shows\",\"parent\":\"SXM\"},{\"type\":\"shows\",\"id\":\"howard\",\"name\":\"Howard Stern\",\"parent\":\"shows\"},{\"type\":\"shows\",\"id\":\"howardstern\",\"name\":\"Howard Stern\",\"parent\":\"howard\"}]",
"sports": "[]"
}
}
How can i remove the backslashes? So the output is like:
{
"tags": {
"channels": " [{"type":"channel","id":"channel","name":"Channel","parent":"SXM"}]",
"shows": "[{"type":"shows","id":"shows","name":"Shows","parent":"SXM"},{"type":"shows","id":"howard","name":"Howard Stern","parent":"shows"}....
There were few other posts, but none explained this.
The problem is caused by this:
tjsonObject.addProperty("channels", gson.toJson(channelsList));
What that is doing is converting channelsList to a string containing a representation of the list in JSON, then setting the property to that string. Since the string contains JSON meta-characters, they must be escaped when the strings are serialized ... a second time.
I think that you need to do this instead:
tjsonObject.add("channels", gson.toJsonTree(channelsList));
That should produce this:
{
"tags": {
"channels":
[{"type":"channel","id":"channel","name":"Channel","parent":"SXM"}],
"shows":
[{"type":"shows","id":"shows","name":"Shows","parent":"SXM"},
{"type":"shows","id":"howard","name":"Howard Stern","parent":"shows"}
....
That is slightly different to what your question asked for, but it has the advantage of being syntactically valid JSON!
String mainJsonStr = mainjsonObject.toString();
mainJsonStr = mainJsonStr.replace("\\\\", ""); //replace the \
System.out.println(mainJsonStr);
The problem is that gson.toJson returns a String, and
tjsonObject.addProperty("channels", gson.toJson(channelsList));
this will add channels as a string and not as a JSON object.
One possible solution is to convert the string returned from gson.toJson to JSON object first then add it to the parent JSON object like
Gson gson = new GsonBuilder().create();
JsonObject tjsonObject = new JsonObject();
tjsonObject.put("channels", new JsonObject(gson.toJson(channelsList)));
tjsonObject.put("shows", new JsonObject(gson.toJson(showsList)));
this will treat channels and shows as JSON object
All strings in java have to escape quotes in them. So jsonInString should have slashes in it. When you output jsonInString though it shouldn't have the quotes. Are you looking at it in a debugger or something?
Just parse json directly and check - will get the output
above solution is not working anymore since GSON 2.8.*
use gson.toJsonTree(jsonText).getAsString(); instead
Good day!
I have an array of json objects like this :
[{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":0
},
{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":4
}]
For some reasons I need to split then to each element and save to storage. In the end I have many objects like
{ "senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":0
}
{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":4
}
After some time I need to combine some of them back into json array.
As I can see - I can get objects from storage, convert them with Gson to objects, out objects to a list, like this:
String first = "..."; //{"senderDeviceId":0,"recipientDeviceId":0,"gmtTimestamp":0,"type":0}
String second = "...";//{"senderDeviceId":0,"recipientDeviceId":0,"gmtTimestamp":0,"type":4}
BaseMessage msg1 = new Gson().fromJson(first, BaseMessage.class);
BaseMessage msg2 = new Gson().fromJson(second, BaseMessage.class);
List<BaseMessage> bmlist = new ArrayList<>();
bmlist.add(msg1);
bmlist.add(msg2);
//and then Serialize to json
But I guess this is not the best way. Is there any way to combine many json-strings to json array? I rtyed to do this:
JsonElement elementTm = new JsonPrimitive(first);
JsonElement elementAck = new JsonPrimitive(second);
JsonArray arr = new JsonArray();
arr.add(elementAck);
arr.add(elementTm);
But JsonArray gives me escaped string with json - like this -
["{
\"senderDeviceId\":0,
\"recipientDeviceId\":0,
\"gmtTimestamp\":0,
\"type\":4
}","
{
\"senderDeviceId\":0,
\"recipientDeviceId\":0,
\"gmtTimestamp\":0,
\"type\":0
}"]
How can I do this?
Thank you.
At the risk of making things too simple:
String first = "...";
String second = "...";
String result = "[" + String.join(",", first, second) + "]";
Saves you a deserialization/serialization cycle.
I have a string I would like to put into an ArrayList of Strings. The string is basically a JSONObject so I might just be using the wrong methods.
The way the string looks is:
String all = "{"users":
[
[{"login":"username1"},{"password":"test1"},{"index":"1"}],
[{"login":"username2"},{"password":"test2"},{"index":"2"}]
]}";
All I want is the JSONObject values so my pattern gives me this String:
String part = "[
[{"login":"username1"},{"password":"test1"},{"index":"1"}],
[{"login":"username2"},{"password":"test2"},{"index":"2"}]
]";
This is what I want:
user[0] = "[{"login":"username1"},{"password":"test1"},{"index":"1"}]";
user[1] = "[{"login":"username2"},{"password":"test2"},{"index":"2"}]";
When I try to group everything in between the inner [ ] it just returns everything in the outer [ ].
I have tried:
String[] user = new String[20];
Pattern p = Pattern.compile("(\\[\\{.*\\}\\])");
Matcher m = p.matcher(part);
while(m.find()){
user = m.group().split("\\],\\[");
}
This approach gets rid of the ],[ which I'm using as a delimiter.
Class User {
private String username;
private String password;
}
Class Users{
LinkedList<User> users;
}
You can use any available JSON marshallers like Jackson etc to deserialize the string into a Users.
So I took the advice from the comment section and sure enough using JSON methods was the way to go. I would still like to see if it was possible to accomplish with regular expressions.
ArrayList<String> myList = new ArrayList<String>();
JSONObject obj = new JSONObject();
JSONArray arr = new JSONArray();
obj = {"user":"[[{},{},{}],[{},{},{}]]";
// This gives me the outer JSONArray
arr = obj.getJSONArray("user");
// This iterates through the outer JSONArray assigning each inner JSONArray
// to my ArrayList as strings.
for( int i = 0; i < arr.length(); i++){
myList.put(arr.getJSONArray(i).toString());
}
I'm trying some code where I want to compare strings i've grabbed from json to certain values. However the if statements never trigger. I have confirmed the values of the instances are set properly, and can be printed out.
//MAKING CLASSES
Collection collection = new ArrayList();
Event ev = new Event();
ev.name = "sven";
ev.source = "src10";
Event2 ev2 = new Event2();
ev2.name = "type";
ev2.data = "somedata";
collection.add(ev);
collection.add(ev2);
//MAKING A BUNCH OF CLASSES TO JSON
Gson gson = new Gson();
String json = gson.toJson(collection);
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(json).getAsJsonArray();
//JSON TO JAVA
for (int i = 0; i < array.size(); i++) {
JsonObject nameObject = array.get(i).getAsJsonObject();
String nameString = nameObject.get("name").toString();
if (nameString.equals("sven")) {
System.out.println("this is sven");
Event event = gson.fromJson(array.get(i), Event.class);
}
else if (nameString.equals("type")) {
System.out.println("this is type");
Event2 event2 = gson.fromJson(array.get(i), Event2.class);
}
else{
System.out.println("nothing");
}
}
According Gson API your call to 'nameObject.get("name")' will return JsonElement. This means you should use 'getAsString()' method instead of 'toString()':
String nameString = nameObject.get("name").getAsString();
'toString()' method is designed (in general) for debugging purposes. And should be used very carefully in program logic.
You need to know that the implementation of toString() in JsonElement class is such that it will return the String inclusive of "".
To make it easier to understand look into the following code
JsonObject json = new JsonObject();
json.addProperty("hello", "tata");
System.out.println(json.get("hello").toString()); // Prints "tata"
System.out.println(json.get("hello").getAsString()); // Prints tata
so internally your code is comparing "sven" and sven which will return not equal
We have to parse a json structure similar to below.
project {
header {
}
pool {
}
cmp {
name = "";
id = "";
desc = "";
cmp [
{
name = "";
id = "";
desc = "";
}
{
name = "";
id = "";
desc = "";
}
{
name = "";
id = "";
desc = "";
cmp [
{
name = "";
id = "";
desc = "";
}
}
}
}
The issue is, cmp element is present in the json infinitly (and it is recursive too).
The cmp element contains lots of properties other than name, id and desc. But we need only name, id and desc to extract from the jSON.
I can able to parse the JSON string using com.json.parsers.JSONParser. But populating the parsed JSON to a model class/bean class is not working. It may be a simple logic. But I cannot. Please help...
The json file is generated as an output of one modeling software.
I want to parse this, using java. Can somebody help me to parse this?
Hope I have explained the issue correctly. Your help will be helpful for us.
You can do this with Jackson, just create your object with all the fields that may or may not be present in the message. All the fields not present in the message will end up as null (or default value for primitives) in the resulting object.
Just have the object contain a copy of itself and that will handle the recursion
#XmlRootElement
public class Foo {
Foo recursiveFoo; // will be null or another instance of Foo
int intData; // Will be 0 or an integer value
String strData; // Will be null or a String value
// Getters and setters here
}
Take a look at Google Gson library. With it you can do things like:
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
//(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
//==> json is {"value1":1,"value2":"abc"}
//(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
//==> obj2 is just like obj