split JSON and string in android - java

My HTTP Request responds with combination of string and JSON, something like this:
null{"username:name","email:email"}
I need only the JSON part.
I directly tried parsing as json object, which was not right of course. I tried splitting it: serverResponse.split("{"), but android does not allow to parse with this character because it is not a pattern. Any suggestion how i can achieve this?

String.split uses regular expressions, and since '{' is a special character in regular expressions, you should escape it like this: serverResponse.split("\\{").

It would be better to change the server side, but you can also just use split. The only thing you need to do is escape your {.
String json = serverResponse.split("\\{")[1];

It is a bad idea and a bad practice to split a Json. If one day it you change on the serve side, it may pick a wrong part of your Json Object.
I recommend you to PARSE it, even if it is simple and small.

Related

Split character is not recognized

As I looked for a reliable character for splitting strings, I found out an earlier post about using "((char)007)" as a split character so i decided to use that for a request/response project I'm building.
But when I send data with "((char)007)" between data parts that need to be seperated, the data arrives at the other end of the socket like this instead "teq□weq□1231□21231".
So splitting this data properly is unsuccessful at the moment. Any ideas about why this happens and what kind of approach I might follow to fix this, what else I can use for splitting, any ideas would be appreciated, thanks.
If you are printing control characters (BELL) then your console may not print it out properly.
In any case, consider just sending a structure like a serialized object (be careful with deserializing user-supplied content) or perhaps JSON. Any structure with a standardized format will do better in the long term versus arbitrary splitting on a magic character

regex to replace the value of a key in a json file

I want to make a regex so I can do a "Search/Replace" over a json file with many object. Every object has a key named "resource" containing a URL.
Take a look at these examples:
"resource":"/designs/123/image.jpg"
"resource":"/designs/221/elephant.gif"
"resource":"/designs/icon.png"
I want to make a regex to replace the whole url with a string like this: localhost:8080/filepath.
This way, the result would be:
"resource":"localhost:8080/designs/123/image.jpg"
"resource":"localhost:8080/designs/221/elephant.gif"
"resource":"localhost:8080/designs/icon.png"
I'm just starting with regular expressions and I'm completely lost. I was thinking that one valid idea would be to write something starting with this pattern "resource":"
How could I write the regular expression?
The easiest method is probably just to replace "resource":"/ with "resource":"localhost:8080/. You don't even need a regex for this (but if you do you just have to escape some stuff).
With vim this would be
:%s/"resource":"\(.*\)"/"resource":"localhost:8080\1"
this should be easily transferable to java.

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.

Simple way to remove escape characters from this JSON date

In my android application, my JSON date is returned as this:
\/Date(1323752400000)\/
Is there a simple way to remove the escape characters? (This is being sent from a WCF service to an Android application). I am already using StringEscapeUtils.unEscapeHtml4 to decode the entire serialized object.
actully this not works as it throws java.util.regex.PatternSyntaxException instead of using that use
myJsonString=myJsonString.replaceAll("\\\\","");
it works fine
On the receiving end, if you really want to, you could just do myJsonString = myJsonString.replaceAll("\\","");
But do note that those escape characters in no way make the JSON invalid or otherwise semantically different -- the '/' character can be optionally escaped with '\' in JSON.
You can use Apache Commons lang:
StringEscapeUtils.unescapeJava(stringToUnEscape);
Class Ref : https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html

Categories