How to Parse JSON from a Java Httpresponse

How do I parse JSON from a Java HTTPResponse?

Two things which can be done more efficiently:

  1. Use StringBuilder instead of StringBuffer since it's the faster and younger brother.
  2. Use BufferedReader#readLine() to read it line by line instead of reading it char by char.

HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);

If the JSON is actually a single line, then you can also remove the loop and builder.

HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONArray finalResult = new JSONArray(tokener);

Parsing a JSON from HTTP Response in Java

Better and easier to use Gson

Gson gson = new Gson;
NameBean name = gson.fromJson(content.toString(),NameBean.class)

NameBean is the object where you persist the json string.

public class NameBean implements Serializable{
public String name;
public String lastname;
public Int age;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

public Int getAge() {
return age;
}

public void setAge(Int age) {
this.age = age;
}

}

Get a JSON object from a HTTP response

The string that you get is just the JSON Object.toString(). It means that you get the JSON object, but in a String format.

If you are supposed to get a JSON Object you can just put:

JSONObject myObject = new JSONObject(result);

Parsing a HttpResponse JSON in Java

According to JsonSimple's JsonObject documentation it takes map in the constructor but not a String. So the error you are getting what it says.
You should use JSONParser to parse the string first.
Its also better to provide the encoding as part of EntityUtils.toString say UTF-8 or 16 based off your scenario.

IOUtils.toString() from Apache Commons IO would be a better choice to use too.

Parsing JSON from HTTPResponse

I haven't used that particular API, but judging by the fact that the object is named JSONArray (keyword: array) I'm going to guess it expects an array. Using JSON, an array has to begin with a [ and end with ]:

[1, 2, 3, 4]

It can contain objects:

[{}, {}, {}]

Note how the objects begin with { and end with }, unlike the arrays:

{
"name": "My Object!"
}

Since your JSON data looks more like an {object} than an [array] maybe you should try using JSONObject instead.

Really though you have two options: you can change the JSON data to be an array, or you can change the Java code to use JSONObject. (One or the other; NOT both.)

Changing the JSON data

As simple as adding a [ at the beginning and ] at the end:

[
{
"ipinfo": {
"ip_address": "4.2.2.2",
"ip_type": "Mapped",
"Location": {
"continent": "north america",
"latitude": 33.499,
"longitude": -117.662,
"CountryData": {
"country": "united states",
"country_code": "us"
},
"region": "southwest",
"StateData": {
"state": "california",
"state_code": "ca"
},
"CityData": {
"city": "san juan capistrano",
"postal_code": "92675",
"time_zone": -8
}
}
}
}
]

Changing the Java

The final Java would look a little something like:

// OLD CODE
//JSONArray jsonArray = new JSONArray(builder.toString());
//for (int i = 0; i < jsonArray.length(); i++) {
// JSONObject jsonObject = jsonArray.getJSONObject(i);
//}
// END OLD CODE
JSONObject jsonObject = new JSONObject(builder.toString());

(Again, one or the other; NOT both.)

How to parse only 1 variable from JSON HTTP response Spring Boot

Try this.

String input = "{\r\n"
+ " \"table\": \"A\",\r\n"
+ " \"currency\": \"usd\",\r\n"
+ " \"code\": \"USD\",\r\n"
+ " \"rates\": [\r\n"
+ " {\r\n"
+ " \"no\": \"073/A/NBP/2021\",\r\n"
+ " \"effectiveDate\": \"2021-04-16\",\r\n"
+ " \"mid\": 3.7978\r\n"
+ " }\r\n"
+ " ]\r\n"
+ "}";
String midValue = input.replaceFirst("(?s).*\"mid\"\\s*:\\s*([-.\\d]+).*", "$1");
System.out.println(midValue);

output:

3.7978


Related Topics



Leave a reply



Submit