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,785
  • 2
  • 31
  • 38
Maria
  • 169
  • 1
  • 3
  • 11

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-
  • 75,269
  • 21
  • 115
  • 152
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,513
  • 2
  • 31
  • 49
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
  • 413
  • 2
  • 9