0

I request a servlet and it returns me JSON structure correctly but combined with "null"

null{"name":Maria,"totalPrice":17.49}

How can I remove null value in the first line?

I am using the following code to get JSON-Servlet:

BufferedReader reader = new BufferedReader(new InputStreamReader(
    ((HttpURLConnection) (new URL(the_url)).openConnection()).getInputStream(),
        Charset.forName("UTF-8")));

String line;
String returnString = null;

while ((line = reader.readLine()) != null) {
    returnString += line;
}

reader.close();
out.write(returnString);
Emil Sierżęga
  • 1,528
  • 2
  • 31
  • 36
Maria
  • 159
  • 1
  • 3
  • 10
  • about null - could it be so it returns JSONP? Try to access servlet url with ?jsonp=test or ?callback=test – chro Dec 02 '13 at 13:42

3 Answers3

2

You're starting with a null String variable, not an empty one, so when you add them together the null value gets replaced with "null". Use returnString = "" instead. Better yet, use a StringBuilder:

StringBuilder result = new StringBuilder();

while ((line = reader.readLine()) != null) {
    result.append(line);
}

reader.close();
out.write(result);
chrylis -cautiouslyoptimistic-
  • 72,004
  • 20
  • 117
  • 147
0

Simply use for example

String yourNewJsonString = stringWithNull.substring(4);

as char with number 4 is { in your String.

BTW, please read Parsing JSON Object in Java and use it for parsing JSON.

Community
  • 1
  • 1
Eel Lee
  • 3,434
  • 2
  • 30
  • 45
0

Today I've replied a similar question (How do I pre parse a JSON String? )

The only problem here is that you have to pretend that the producer of JSON data produces them in a consistent manner. Work (if you can) on the JSON provider, not your client.

(being pragmatic) the reply form @eel-lee is what I would do if fixing the Servlet is unviable (?? really ??).

Community
  • 1
  • 1
Giupo
  • 403
  • 2
  • 9