Fetch String with special character from json using JSONObject - java

I have a JSON object with special character in it.
The format is as follows:
"field1": "result1", "field2": "\uabc\udef\ughi"
I get the string for each of the keys as
JSONObject jsonObj = new JSONObject();
String s1 = jsonObj.getString("field1");
String s2 = jsonObj.getString("field2");
When I print s2, I get weird characters as output. I know, "\u" is doing all the weirdness and I do not want that. I just want to get the string for field2 as it is. Sadly, I cannot modify the JSON object at source.
Any solution to this scenario.

Related

Text to Json in Java (list in text)

I have the following text which is returned by an API that I call:
{"identified_faces_names": "[\"omar\", \"elhoussinep\"]"}
when I pass this text to JSONParse to parse it, it give me the following exception:
Exception in thread "main" Unexpected character (o) at position 0.
Code used to parse the text to json:
String s = new String("{\"identified_faces_names\": \" [\"omar\",\"elhoussinep\"]\"}");
JSONParser parser = new JSONParser();
Object obj = parser.parse(s);
Did you definitely mean to enclose ["omar", "elhoussinep"] in quotes? Is that definitely intended to be a String value containing string quotes? Or is it intended to be an array of strings?
If identified_faces_names is intended to be an array of strings then the valid JSON is:
{
"identified_faces_names": [
"omar",
"elhoussinep"
]
}
This is parseable, without error, like so:
String s = new String("{\"identified_faces_names\": [\"omar\",\"elhoussinep\"]}");
JSONParser parser = new JSONParser();
Object obj = parser.parse(s);
If identified_faces_names is intended to be a String containing quotes you must escape the quotes inside the string. The valid JSON is:
{
"identified_faces_names": "[\\\"omar\\\",\\\"elhoussinep\\\"]"
}
This is parseable, without error, like so:
String s = new String("{\"identified_faces_names\": \" [\\\"omar\\\",\\\"elhoussinep\\\"]\"}");
JSONParser parser = new JSONParser();
Object obj = parser.parse(s);
So, in summary, I'd suggest revisiting the JSON to determine whether it is an array of strings or a string which contains quotes, if the latter then you have to escape those quotes.
FWIW, you can use JSONLint to check whether the JSON is valid. Using this you can see that your original JSON ({"identified_faces_names": "["omar","elhoussinep"]"}) was not valid and that the first invalid character is the "o" in "omar" and that's deemed invalid because it follows "[" which is deemed to be a complete String.
Use this String {"identified_faces_names": [\"omar\", \"elhoussinep\"]}. It is correct and will parse.

Convert any simple string to JSON in Java

I have string like:
String metadata = "{ Item: {Owner:John, About:{website:www.john.com/about, firstName:William, lastName:Shakespeare, date:1/2/2000, books:[Othello, R&J], shelf:[12/3/4, 14/5/6, 17/8/6]}}}"
I want to convert this metadata into JSON format. But because of missing quotes I was not able to convert it.
I can write a code that could do parsing and add quotes, that does not becomes flexible for any string to make it into JSON. (Since this metadata is prone to changes in future).
Is there a way to add quotes to any string to make it into JSON?
Or how can be this generalized so that simple string is converted into JSON. Do we have any library in Java that converts?
Code snippets will be really helpful to understand, if no library is there.
Well, I prefer not to use any external library.
Your string seems to use fancy incoherent notation: colons and equal signs to separate keys, unquoted strings, dates with multiple formats...
How is it generated in the first place? It may be easier to change how that string is generated than parsing it again.
To parse the string, you must first determine the rules on how to break it apart (the grammar). Incoherent as it is, this parser would have no end of special cases.
public static void main(String[] args){
String metadata = "{ Item: {Owner:John, About:{website:www.john.com/about, firstName:William, lastName:Shakespeare, date:1/2/2000, books:[Othello, R&J], shelf:[12/3/4, 14/5/6, 17/8/6]}}}";
String json = "";
StringTokenizer st = new StringTokenizer(metadata, "([^:{}, ])", true);
StringTokenizer stkey = new StringTokenizer(metadata, "([^:{}, ])", false);
while(stkey.hasMoreTokens()){
String s1 = stkey.nextToken();
while(st.hasMoreTokens()){
String s2 = st.nextToken();
if(s1.equals(s2)){
json += "\"" + s2.trim() + "\"";
break;
} else {
json += s2;
}
}
}
while(st.hasMoreTokens()){
json += st.nextToken();
}
System.out.println(json);
JSONObject jo = JSONObject.fromObject(json);
}
Only can regarded every values as string. you can control regex repression to do better.

split string and get the value using regex from a complicated string

I have a string like this {"product_tags":"yin_yang,yin yang"}.
what I want to do is just avoid everything else other than yin yang. There is two strings but I just want the first one.
Note that in some cases even if the second string is not available I want to get the same result. And that string might change so it is not necessary that the string will be always yin_yang sometimes it can be motorbike or anything else.
It Look like JSON String Use the JSONParser in java
JSONObject jobject=new JSONObject(STRING);
String value=jobject.getString("product_tags");
EDITED
Using REGEX
String json="{\"product_tags\":\"yin_yang,yin yang\"}";
json=json.replaceAll("([{}]+)", "");
String value[]=json.split(":");
System.out.print(value[1]);
You can use StringTokenizer to parse your string
String str ="{\"product_tags\":\"yin_yang,yin yang\"}";
StringTokenizer to = new StringTokenizer(str,":}");
while(to.hasMoreTokens()){
String firstString = (String) to.nextElement();
String secondString = (String) to.nextElement();
System.out.print(secondString);
}

How to avoid quotes around string values while creating JSONObject

I am trying to create JSON query string for MongoDB, In order to support regular expression I need to create JSON string that has values without quotes. How do accomplish this in java,
Here is the example of what I am trying to do,
JSONObject obj= new JSONObject();
String title = "gro";
obj.put("title", "/.*" + title + ".*/");
Result is
{"title ":"/.*gro.*/"}
Above is no longer treated as a regular expression by MongoDB. What i wanted is,
{"title ":/.*gro.*/}
So that MongoDB treats it as a regular expression. Is there any way to accomplish this in java?
The / delimited regular expression syntax is a JavaScript construct. In Java you have to use java.util.regex.Pattern like this:
BasicDBObject query = new BasicDBObject("title", Pattern.compile(".*gro.*"));
Try this,
JSONObject obj= new JSONObject();
String title = "gro";
String startExpr = "/.*";
String endExpr = ".*/";
obj.put("title", startExpr + title + endExpr );

Json and Java. From String to JSONObject: issues

I'm using the library org.json.
I have a string like this (quotes can't appear in field_n)
{field1=value1, field2=value2} (say it `val`)
This string is obtained from an Hashtable<String, Object>.
I create a JSONObject from that string, obtaining:
{"field1":"value1", "field2":"value2"}
The issue arises when in the value value_n quotes (or newlines and carriage return) appear.
I've tried to escape the string in this way:
value = value.replace("\\", "\\\\");
value = value.replace("\"", "\\\"");
value = value.replace("\r", "\\r");
value = value.replace("\n", "\\n");
but I always obtain the org.json.JSONException: Expected a ',' or '}' at ... [character ... line 1] when I try to create the JSONObject with:
JSONObject json = new JSONObject(val);
In order to create JSON from map, use:
new JSONObject(myMap);
Another related issue:
quotedStr = JSONObject.quote(val.trim());
will qoute all needed values as it says:
Produce a string in double quotes with backslash sequences in all the right places

Categories

Resources