Regex To Extract An Object From A JSON String - java

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,

Related

Need help Parsing String in java

I am getting Messages from Server So that I need to Parse the Contents of the Messages.
Currently I received the Message and converted it into the String specified below,
Lat:+1290.9890N
Long:+9098.987890E
Spd:90km/h
So from the above String, I need to get the Value of Lat,Long and speed ..How to do that in Java..Thanks in advance..
There are many ways, use substring function http://docs.oracle.com/javase/6/docs/api/java/lang/String.html. Try by your self.
You can use split, substring or other ways to do it. I would recommend to use pojo for this to avoid any issues in processing string like Sting index out of bounds other possible exceptions. It will be cleaner and easier to manage as your message seems pretty static in its format.
Create a string builder for each line.
Iterate through each existing string.
Call isDigit() on each item in the string.
If isDigit == true, append the digit to the string builder.
Cast the string builder to a long
You could create a Scanner and call findInLine() with a Pattern regular expression that will only find floating point numbers e.g. (0..9)*.(0..9)*

Java Extract part of string

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.

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 can I convert String to Map with a Map as one of the "values"?

Could someone please help me to convert this String into a Map...
String str = "{"id":1,"result":[{"employeeId":131969,"id":1164299,"name":"Prosjekt","javaClass":"no.tripletex.tcp.model.Project","number":"","displayName":"Prosjekt"}]}"
From the format of your string, it seems like you need a JSON parser, no matter what language you are using.
There are many json parser here
Here is a Java json parser, you may follow its example.

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