Escape " between to Strings - java

I'm getting an Json and then using Gson to deserialize it in an object where value is a String not an object.. so i'm trying to put that object into a String variable - not deserialized
I want to do something like this:
"{value" : {"id":"2"}} -> {"value" : "{\"id\":\"2\"}"}
I replaced the "value" : { with "value" : "{ like this:
result = result.replace("\"value\" : {", "\"value\" : \"{");
and then I replaced the }} like this:
result = result.replace("}}", "}\"}");
And my result was (after replacing everything):
{"value" : "{"id":"2","name":"game2"}"}
the only problem now: i also want to replace the " with \" but only inside the "{ ... }" I can't figure that out.
EDIT:
Incoming Json:
{"path" : "/gdi/games/2", "key" : "detail", "value" : {"id":"2","name":"game2"}},
{"path" : "/gdi/games/4", "key" : "detail", "value" : {"id":"4","name":"game4"}},
{"path" : "/gdi/games/6", "key" : "detail", "value" : {"id":"6","name":"game6"}}
The problem: value: could be anything (text) so I only want to store everything which cames between { } in my Object which become deserialized in an object that looks like:
String path;
String key;
String value;
To achieve this I have to escape the object (which is in "value") like it is String - After escaping that Gson can deserialize it for me.
Json needed:
{"path" : "/gdi/games/2", "key" : "detail", "value" : "{\"id\":\"2\",\"\name\":\"game2\"}"},
{"path" : "/gdi/games/4", "key" : "detail", "value" : "{\"id\":\"4\",\"\name\":\"game4\"}"},
{"path" : "/gdi/games/6", "key" : "detail", "value" : "{\"id\":\"6\",\"\name\":\"game6\"}"}

This does the trick:
input = input.replaceAll("(?=\"[^{}]*\\})", "\\\\");
It uses a look ahead to assert that the next curly bracket found after a double quote is a right curly - meaning the double quote must be within a pair of curly brackets.
The replacement term is a literal backslash - four backslashes needed due to double-escape: one for java string literal, one for regex escape.
Here's some test code using your sample input an producing your expected output:
String input =
"{\"path\" : \"/gdi/games/2\", \"key\" : \"detail\", \"value\" : {\"id\":\"2\",\"name\":\"game2\"}}," +
"{\"path\" : \"/gdi/games/4\", \"key\" : \"detail\", \"value\" : {\"id\":\"4\",\"name\":\"game4\"}}," +
"{\"path\" : \"/gdi/games/6\", \"key\" : \"detail\", \"value\" : {\"id\":\"6\",\"name\":\"game6\"}}";
input = input.replaceAll("(?=\"[^{}]*\\})", "\\\\");
System.out.println(input);
Output:
{"path" : "/gdi/games/2", "key" : "detail", "value" : {\"id\":\"2\",\"name\":\"game2\"}},
{"path" : "/gdi/games/4", "key" : "detail", "value" : {\"id\":\"4\",\"name\":\"game4\"}},
{"path" : "/gdi/games/6", "key" : "detail", "value" : {\"id\":\"6\",\"name\":\"game6\"}}

You can use Jackson library to map data to a class.
http://www.journaldev.com/2324/jackson-json-processing-api-in-java-example-tutorial
For printing backslashes - example
public static void main(String[] args) {
String a="{\"id\":\"2\",\"name\":\"game2\"}";
System.out.println("Before - "+a);
System.out.println("After - "+a.replace("\"", "\\\""));
}
output -
Before - {"id":"2","name":"game2"}
After - {\"id\":\"2\",\"name\":\"game2\"}

you just need to add double \ if you want to add "\"
for example: System.out.println("\\"");
print this statement you will get : \"
String abc: "\\"";

Related

There is a way to send json string or even JSONObject to POSTMAN without a slash before every double quote?

After alot of research i knew that JAVA does that internally. Tried to replace the slashes with empty string .Also tried to use some libraries to parse String to JSONObject But Same result, A slash before every double qoute..
Request To POSTMAN:
{
"MTI": "0100",
"2": "4655206331051889",
"3": "000000",
"4": "000000012300",
"7": "0321054133",
"11": "001205",
"14": "0325",
"18": "5399",
"22": "022",
"25": "00",
"35": "2312312332",
"37": "206305000014",
"41": "29110001",
"42": "1001001",
"49": "840",
"transactionid": "12",
"co-ordinates": "3042304,293572945"
}
Code:
StringBuilder transactionReq = new StringBuilder();
for (Object o : responseMessage.getChildren().keySet()) {
int key = (Integer) o;
// The Transaction Request Body that has been Received in JSON Format.
transactionReq
.append('"')
.append(key)
.append('"')
.append(" : ")
.append('"')
.append(responseMessage.getValue(key))
.append('"')
.append(" ,");
}
transactionReq
.insert(0, "{")
.deleteCharAt(transactionReq.length() - 1)
.deleteCharAt(transactionReq.length() - 1)
.insert(transactionReq.length(), "}");
response.setMessage(transactionReq.toString().replaceAll("\\\\", ""));
System.out.println(transactionReq.toString());
Console:
{
"message": "{"0" : "0110" ,"1" : "4655206331051889" ,"3" : "000000" ,"4" : "000000012300" ,"6" : "000000000012" ,"7" : "0321054133" ,"11" : "001205" ,"14" : "0325" ,"18" : "5399" ,"22" : "022" ,"25" : "00" ,"35" : "2312312332" ,"37" : "549684 " ,"38" : "84738 " ,"39" : "00" ,"41" : "29110001" ,"42" : "1001001 " ,"49" : "840" ,"57" : "3042304" ,"58" : "293572945"}"
}
Response From POSTMAN:
{
"message": "{\"0\" : \"0110\" ,\"2\" : \"4655206331051889\" ,\"3\" : \"000000\" ,\"4\" : \"000000012300\" ,\"6\" : \"000000000012\" ,\"7\" : \"0321054133\" ,\"11\" : \"001205\" ,\"14\" : \"0325\" ,\"18\" : \"5399\" ,\"22\" : \"022\" ,\"25\" : \"00\" ,\"35\" : \"2312312332\" ,\"37\" : \"549684 \" ,\"38\" : \"84738 \" ,\"39\" : \"00\" ,\"41\" : \"29110001\" ,\"42\" : \"1001001 \" ,\"49\" : \"840\" ,\"57\" : \"3042304\" ,\"58\" : \"293572945\"}"
}
The Output in the console proves that iam sending a right json request..
But the response the shows in postman says the opposite..
Happy to hear any Explanation...
Thanks in Advance
It`s built in java, Java treats Strings that way , So i used a DTO To avoid that

Fetch Inner Json of Array using Mongo Cursor

Using Cursor need to fetch values of Inner Json which is in Array
Document looks like this
{
"_id" : ObjectId("5772932ce4b0be6213704c81"),
"employerId" : "57728cd7e4b0be6213704b17",
"jobSeekerId" : "5706426ae4b0c7ea74fda18b",
"readByJobSeeker" : true,
"readByJobEmployer" : true,
"interestChat" : [
{
"userChat" : "is this job avaliable ",
"lastChatRole" : "JOBSEEKER",
"lastChatTime" : ISODate("2017-08-10T15:20:25.017Z"),
"jobSeekerAcknowledgeFlag" : true,
"connectionCounterIncreamented" : false
}
],
"createdDate" : ISODate("2016-06-28T15:09:32.564Z"),
"lastModifiedDate" : ISODate("2017-08-10T15:31:12.564Z"),
"version" : NumberLong(20),
"active" : true
}
Issue is using query
db.interest.find({"interestChat":{$exists:true}}).forEach(function(myChat){print ("interest :: "+ myChat.interestChat); } ).pretty()
Not able to fetch data from Array as output come out as
interest :: [object BSON]
Need to fetch values of Inner json
The function print is not meant to bring json/bson objects.
Try printjson instead.
db.interest.find({"interestChat":{$exists:true}})
.forEach(function(myChat){
printjson({"interest": myChat.interestChat});
})
OR just printjson(myChat.interestChat);

Regex query MongoDB Performance issue

i have Mongodb collection which contains single field , each day i am receiving 31000 documents and in the collection i have almost 6 months data
Here is how my data looks like in database
{
"_id" : ObjectId("59202aa3f32dfba00d0773c3"),
"Data" : "20-05-2017 18:38:13 SYSTEM_000_00_SAVING ",
"__v" : 0
}
{
"_id" : ObjectId("59202aa3f32dfba00d0773c4"),
"Data" : "20-05-2017 18:38:13 SyTime_000_09_00:00 ",
"__v" : 0
}
here is my code for query
DBObject query = new BasicDBObject();
Pattern regex = Pattern.compile("20-05-2017");
query.put("Data", regex);
i have created index but its still slow
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "NOB_SRB.fdevices"
},
{
"v" : 1,
"unique" : true,
"key" : {
"Data" : 1.0
},
"name" : "Data_1",
"ns" : "NOB_SRB.fdevices"
}
]
Add a start of input anchor ^ to the start of the regex:
Pattern regex = Pattern.compile("^20-05-2017");
Because your regex does not have an anchor, the entire field is searched for the date anywhere in it, which requires every character in the field to be compared.

Read out elements of a string in specific order

For some reasons I have to use a specific string in my project. This is the text file (it's a JSON File):
{"algorithm":
[
{ "key": "onGapLeft", "value" : "moveLeft" },
{ "key": "onGapFront", "value" : "moveForward" },
{ "key": "onGapRight", "value" : "moveRight" },
{ "key": "default", "value" : "moveBackward" }
]
}
I've defined it in JAVA like this:
static String input = "{\"algorithm\": \n"+
"[ \n" +
"{ \"key\": \"onGapLeft\", \"value\" : \"moveLeft\" }, \n" +
"{ \"key\": \"onGapFront\", \"value\" : \"moveForward\" }, \n" +
"{ \"key\": \"onGapRight\", \"value\" : \"moveRight\" }, \n" +
"{ \"key\": \"default\", \"value\" : \"moveBackward\" } \n" +
"] \n" +
"}";
Now I have to isolate the keys and values in an array:
key[0] = onGapLeft; value[0] = moveLeft;
key[1] = onGapFront; value[1] = moveForward;
key[2] = onGapRight; value[2] = moveRight;
key[3] = default; value[3] = moveBackward;
I'm new to JAVA and don't understand the string class very well. Is there an easy way to get to that result? You would help me really!
Thanks!
UPDATE:
I didn't explained it well enough, sorry. This program will run on a LEGO NXT Robot. JSON won't work there as I want it to so I have to interpret this JSON File as a normal STRING! Hope that explains what I want :)
I propose a solution in several step.
1) Let's get the different parts of your ~JSON String. We will use a pattern to get the different {.*} parts :
public static void main(String[] args) throws Exception{
List<String> lines = new ArrayList<String>();
Pattern p = Pattern.compile("\\{.*\\}");
Matcher matcher = p.matcher(input);
while (matcher.find()) {
lines.add(matcher.group());
}
}
(you should take a look at Pattern and Matcher)
Now, lines contains 4 String :
{ "key": "onGapLeft", "value" : "moveLeft" }
{ "key": "onGapFront", "value" : "moveForward" }
{ "key": "onGapRight", "value" : "moveRight" }
{ "key": "default", "value" : "moveBackward" }
Given a String like one of those, you can remove curly brackets with a call to String#replaceAll();
List<String> cleanLines = new ArrayList<String>();
for(String line : lines) {
//replace curly brackets with... nothing.
//added a call to trim() in order to remove whitespace characters.
cleanLines.add(line.replaceAll("[{}]","").trim());
}
(You should take a look at String String#replaceAll(String regex))
Now, cleanLines contains :
"key": "onGapLeft", "value" : "moveLeft"
"key": "onGapFront", "value" : "moveForward"
"key": "onGapRight", "value" : "moveRight"
"key": "default", "value" : "moveBackward"
2) Let's parse one of those lines :
Given a line like :
"key": "onGapLeft", "value" : "moveLeft"
You can split it on , character using String#split(). It will give you a String[] containing 2 elements :
//parts[0] = "key": "onGapLeft"
//parts[1] = "value" : "moveLeft"
String[] parts = line.split(",");
(You should take a look at String[] String#split(String regex))
Let's clean those parts (remove "") and assign them to some variables:
String keyStr = parts[0].replaceAll("\"","").trim(); //Now, key = key: onGapLeft
String valueStr = parts[1].replaceAll("\"","").trim();//Now, value = value : moveLeft
//Then, you split `key: onGapLeft` with character `:`
String key = keyStr.split(":")[1].trim();
//And the same for `value : moveLeft` :
String value = valueStr.split(":")[1].trim();
That's it !
You should also take a look at Oracle's tutorial on regular expressions (This one is really important and you should invest time on it).
You need to use a JSON parser library here. For example, with org.json you could parse it as
String input = "{\"algorithm\": \n"+
"[ \n" +
"{ \"key\": \"onGapLeft\", \"value\" : \"moveLeft\" }, \n" +
"{ \"key\": \"onGapFront\", \"value\" : \"moveForward\" }, \n" +
"{ \"key\": \"onGapRight\", \"value\" : \"moveRight\" }, \n" +
"{ \"key\": \"default\", \"value\" : \"moveBackward\" } \n" +
"] \n" +
"}";
JSONObject root = new JSONObject(input);
JSONArray map = root.getJSONArray("algorithm");
for (int i = 0; i < map.length(); i++) {
JSONObject entry = map.getJSONObject(i);
System.out.println(entry.getString("key") + ": "
+ entry.getString("value"));
}
Output :
onGapLeft: moveLeft
onGapFront: moveForward
onGapRight: moveRight
default: moveBackward

JSON to Java Object

I'm a little stuck with the following problem.
From a MongoDB I get this JSON string, and I want to get all the valuas of 'photo' and put them in an ArrayList. I've found some examples but they aren't working for me. I'm using GSON but a JSON solution will also be fine.
Return from MongoDB:
[ { "url" : "/photos/avatar-1.jpg" , "photo" : "avatar-1.jpg" , "description" : "test 1"} , { "url" : "/photos/avatar-2.jpg" , "photo" : "avatar-2.jpg" , "description" : "test 2"} , { "url" : "/photos/avatar-3.jpg" , "photo" : "avatar-3.jpg" , "description" : "test 3"} , { "url" : "/photos/avatar-4.jpg" , "photo" : "avatar-4.jpg" , "description" : "test 4"}]
Putting into an ArrayList isn't the problem, but getting the 'photo' value. If someone could give me an example on how to loop through the 4 arrays and a System.out.println of the 'photo' value, that would be great!!
Thanks!
jsonString =[...];
Gson gson = new Gson();
PhotoDTO[] photos = gson.fromJson(jsonString, PhotoDTO[].class);
for(PhotoDTO photo : photos){
System.out.println("photo -> " + photo.getPhoto());
}
PhotoDTO Class Definition
class PhotoDTO
{
String url;
String photo;
String description;
// setters & getters methods
}
Using the excellent json-simple library, you should be able to do something like this:
String json = "[{\"photo\": \"1.png\"}, {\"photo\": \"2.png\"}, " +
"{\"photo\": \"3.png\"}, {\"photo\": \"4.png\"}]";
JSONArray photos = (JSONArray)JSONValue.parse(json);
for (int index = 0; index < photos.size(); index++) {
JSONObject photoObj = (JSONObject)photos.get(index);
System.out.println(photoObj.get("photo"));
}
Obviously replace the literal JSON text with the data that you're fetching from your database.
Another option without creating DTOs, using Gson class StringMap:
String json = "[ { \"url\" : \"/photos/avatar-1.jpg\" , \"photo\" : \"avatar-1.jpg\" , \"description\" : \"test 1\"} , { \"url\" : \"/photos/avatar-2.jpg\" , \"photo\" : \"avatar-2.jpg\" , \"description\" : \"test 2\"} , { \"url\" : \"/photos/avatar-3.jpg\" , \"photo\" : \"avatar-3.jpg\" , \"description\" : \"test 3\"} , { \"url\" : \"/photos/avatar-4.jpg\" , \"photo\" : \"avatar-4.jpg\" , \"description\" : \"test 4\"}]";
Gson gson = new Gson();
Type type = new TypeToken<List<StringMap<String>>>(){}.getType();
List<StringMap<String>> stringMaps = gson.fromJson(json, type);
for (StringMap<String> map:stringMaps) {
System.out.println(map.get("photo"));
}
EDIT
Imports:
import com.google.gson.Gson;
import com.google.gson.internal.StringMap;
import com.google.gson.reflect.TypeToken;

Categories