Java Extract part of string - java

I want to extract the value 0.81 from the following string, but I don't know how. Using JSON doesn't work, because as far as I know it's not proper JSON code.
[{"boundingbox":{"size":{"height":239.23,"width":239.23},"tl":{"y":46.15,"x":166.92}},"name":"152:0.81,","confidence":0.9}]
Do you have any idea how to do that?

If this is JSON, which it appears to be, load it up as a JSON Object and
JSONArray jsonArray = new JSONArray(thatString);
JSONObject jObj = jsonArray.getJSONObject(0);
String name = jObj.getString("name");
Which would then give you a string "152:0.81,", an odd name - however I would then split it:
String[] tokens = name.split(":");
tokens[0] will be 152
tokens[1] will be 0.81,

It actually is valid Json, so you could use Json library (any of them), to load the Json to an Object and access the value - If you're having problems loading this into an Object, perhaps you can change your question and show us the error?
If, by any chance, you might get a response that isn't valid Json, you might use a regex:
If you always have that same pattern, something like:
\"name\":\"\d+:(\d\.\d+),\"
Your value will be in capturing group one.
If you're not sure how to use regexes in Java, just search SO or Google, there's a ton of examples.

Related

org.json.JSONException: Missing value at character 1

I am having an escaped string in a variable and I am trying to make JSON object out of the string. It's throwing the Exception which looks like this :
org.json.JSONException: Missing value at character 1
After thorough research, I couldn't find an answer in a stack overflow.
But finally, I found a clue and got rid of this problem. I want to share the solution so that others won't waste much of their time in this.
If the string is escaped you need to unescape it before trying to make JSONObject out of it. Below is the sample snippet.
String escapedString = StringEscapeUtils.unescapeJava(escapedString);
JSONObject Json = new JSONObject(escapedString);
I open to hear any other best solutions other than what I mentioned here.
Adding further details about your approach -
Deprecated - org.apache.commons.lang3.StringEscapeUtils
Correct reference - org.apache.commons.lang3.StringEscapeUtils

String to JSONObject conversion in Java

I need to convert
{"officeId":1,"clientId":97,"resourceId":97}
Please note that for values I don't have quotes. I have seen similar questions asked and answered, i haven't seen one that looks exactly like this one, i.e values have no quotes in the string to be converted.
Here's the original string from REST server
"{\"officeId\":1,\"clientId\":98,\"resourceId\":98}"
Are you getting an error? You shouldn't be because it's valid JSON. If you quote the numbers, they're now strings instead.
See Can JSON numbers be quoted.
A regular parse will suffice:
JSONObject jsonObj = new JSONObject("{\"officeId\":1,\"clientId\":98,\"resourceId\":98}");

Regex To Extract An Object From A JSON String

I have JSON String I would like to extract a Field from it Using Regex. The field can be an Object, Array, String, int or any type. I Know the other way like looping through all the keys in the JSON and finding it. I would like to know, This can be achieved using Regex or not. Any help would be great.
This can be achieved using Regex or not
Not reasonably, no, because regular expressions are not well-suited to interpreting structures like JSON on their own; as with HTML, you want a proper parser.
Instead, use any of the several Java libraries for parsing the JSON and then traversing its content; there's a list of them at the bottom of the JSON site (I see Gson used a lot, but there are lots of options).
It can be achieved through regex, but it is simply worthless, because the you have to parse out your own variables.
Anyway, lets say we have a method getObject(String key, String JSON)
public String getObject(String key, String JSON) {
Pattern p = Pattern.compile(String.format("\"%s\":\\s*(.*),", key));
Matcher matcher = pattern.matcher(JSON);
if(matcher.find())
return matcher.group();
return null;
}
Note that this only will find the first occurence, you should modify this to your needs.
However, I do recommend a parser which parses the value for you.
It's better to use JSON deserialization tools (e.g. Jackson, GSON), get Object and check,

Using regex to remove JSON quotes

I am being given some JSON from an external process that I can't change, and I need to modify this JSON string for a downstream Java process to work. The JSON string looks like:
{"widgets":"blah","is_dog":"1"}
But it needs to look like:
{"widgets":blah,"is_dog":"1"}
I have to remove the quotes around blah. In reality, blah is a huge JSON object, and so I've simplified it for the sake of this question. So I figured I'd attack the problem by doing two String#replace calls, one before blah, and one after it:
dataString = dataString.replaceAll("{\"widgets\":\"", "{\"widgets\":");
dataString = dataString.replaceAll("\",\"is_dog\":\"1\"}", ",\"is_dog\":\"1\"}");
When I run this I get a vague runtime error:
Illegal repetition
Can any regex maestros spot where I'm going awrye? Thanks in advance.
I believe you need to escape braces. Braces are used for repetition ((foo){3} looks for foo three times in a row); hence the error.
Note: in this case it needs to be double escaping: \\{.
{ and } in regex have special meaning. They are to mention allowed repetition of patterns. So they are to be escaped here.
Use \\{\"widgets\":\"", "\\{\"widgets\": instead of {\"widgets\":\"", "{\"widgets\":.
Since the input string looks to be valid json, your best bet would be to parse it with an actual parser to a map-like structure. Regexes are not the right tools for this. Serializing this structure to to something not quite json would then be relatively simple.
I do wonder if you're better off taking the code for JSONObject and modifying the toString() method to make this a more reliable transformation than using regexps. Here's the source code, and you're looking for invocations of the quote() method
Well, why don't you simply do the following?
1) Decode the first JSON (which is correct with quotes) into varJSON1
2) Get the String "blah" in varJSON1 into varJSON2
3) Then decode the varJSON2

How to add a URL String in a JSON object

I need to add a URL typically in the format http:\somewebsite.com\somepage.asp.
When I create a string with the above URL and add it to JSON object json
using
json.put("url",urlstring);
it's appending an extra "\" and when I check the output it's like http:\\\\somewebsite.com\\somepage.asp
When I give the URL as http://somewebsite.com/somepage.asp
the json output is http:\/\/somewebsite.com\/somepage.asp
Can you help me to retrieve the URL as it is, please?
Thanks
Your JSON library automatically escapes characters like slashes. On the receiving end, you'll have to remove those backslashes by using a function like replace().
Here's an example:
string receivedUrlString = "http:\/\/somewebsite.com\/somepage.asp";<br />
string cleanedUrlString = receivedUrlString.replace('\', '');
cleanedUrlString should be "http://somewebsite.com/somepage.asp".
Hope this helps.
Reference: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replace(char,%20char)
Tichodroma's answer has nailed it. You can solve the "problem" by storing valid URLs.
In addition, the JSON format requires that backslashes in strings are escaped with a second backslash. If the 2nd backslash is left out, the result is invalid JSON. Refer to the JSON syntax diagrams at http://www.json.org
The fact that the double backslashes are giving you problems actually means that the software that is reading the files is broken. A properly written JSON parser will automatically de-escape the strings. The site I linked to above lists many JSON parser libraries written in many languages. You should use one of these rather than trying to write the JSON parsing code yourself.

Categories