user3303274
user3303274

Reputation: 749

split JSON and string in android

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?

Upvotes: 2

Views: 1753

Answers (3)

Pecs Correia
Pecs Correia

Reputation: 71

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.

Upvotes: 1

Slav
Slav

Reputation: 891

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

Upvotes: 4

Niki van Stein
Niki van Stein

Reputation: 10734

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];

Upvotes: 3

Related Questions