2

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?

Slav
  • 786
  • 1
  • 13
  • 25
user3303274
  • 729
  • 2
  • 8
  • 21
  • You can try something similar to these.. http://stackoverflow.com/questions/413071/regex-to-get-string-between-curly-braces-i-want-whats-between-the-curly-brace – Subir Kumar Sao Nov 10 '15 at 12:16

3 Answers3

4

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

Slav
  • 786
  • 1
  • 13
  • 25
3

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];
Niki van Stein
  • 10,564
  • 3
  • 29
  • 62
  • I also don't know why the server side sends null because it is not handled by me. I just had to get json and parse it. Thank you for the helpful reply. – user3303274 Nov 10 '15 at 12:55
  • Probably the server sends JSONP, which is used for javascript, the null is actually the `callback` variable. Try to get the url like: `http:yoururl.com/?callback=` to see if that gives you an empty string in front. – Niki van Stein Nov 10 '15 at 12:57
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.