create json object from request body which contains JSON data - java

My request body contains JSON. i have to read that JSON save it as JSON object. And i don't have any pojo class representing the data in json. i tried this , and this and i am using com.ibm.json.java.JSONObject.i have tried this ,
BufferedReader ne = req.getReader();
StringBuffer jb = new StringBuffer();
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
JSONObject jsonObject = new JSONObject();
jsonObject.put("data", jb.toString());
above implementation is dumb because i am converting request header to string and adding it to jsonobject.

I think you should use public static JSONObject parse( java.lang.String str) in class JSONObject .Also there is no need to convert Reader to String as there are overloaded methods in JSONObject which take Inputstream and Reader eg public static JSONObject parse( java.io.Reader reader)

Related

Loop all data from json in java

I have a problem with Java when I try to display all of content from cmd's elements. So here is my code:
public static void main(String[] args) throws Exception {
// Json Stream Reader
String jsonS = "";
// Connect to web api
URL url = new URL("http://b50172e8.ngrok.io/api/plugin/521100d075c1284b944841394e157744");
// Make Connection
URLConnection conn = url.openConnection();
conn.setRequestProperty("Accept","*/*");
conn.connect();
// Stream reader
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while((inputLine = in.readLine()) != null) {
jsonS+=inputLine;
}
// Read json response
Gson gson = new Gson();
// Json Object
JsonObject jsonObject= gson.fromJson(jsonS, JsonObject.class);
JsonElement data = jsonObject.get("data");
System.out.println(data);
// Close connection
in.close();
}
Output:
[{"cmd":"cmd-1"},{"cmd":"cmd-2"},{"cmd":"cmd-3"}]
I want to use foreach of cmd to display the following:
cmd-1
cmd-2
cmd-3
Try this code. I hope it helps.
public static void main(String[] args) throws Exception {
// Json Stream Reader
String jsonS = "";
// Connect to web api
URL url = new URL("http://b50172e8.ngrok.io/api/plugin/521100d075c1284b944841394e157744");
// Make Connection
URLConnection conn = url.openConnection();
conn.setRequestProperty("Accept","*/*");
conn.connect();
// Stream reader
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while((inputLine = in.readLine()) != null) {
jsonS+=inputLine;
}
// Read json response
Gson gson = new Gson();
// Json Object
JsonObject jsonObject= gson.fromJson(jsonS, JsonObject.class);
JsonArray data = jsonObject.getAsJsonArray("data");
//here data is JsonArray and it contains everithing: [{"cmd":"cmd-1"},{"cmd":"cmd-1"},{"cmd":"cmd-1"}]
data.forEach(el -> {
//Get Json object which has key and value -> {"cmd":"cmd-1"}
JsonObject jo = el.getAsJsonObject();
//get the value as Json element -> "cmd-1"
JsonElement je = jo.get("cmd");
//Then make the json element string
String value = je.getAsString();
System.out.println(value);
});
//System.out.println(data);
// Close connection
in.close();
}

Receive data from a webservice using REST API

I need to get specific data from this API http://countryapi.gear.host/v1/Country/getCountries?pName=Australia, convert it to String and write out on the console. I want to get data only for Australia. How can I get data in String format only for Name and Alpha2Code like this:
Australia, AU? I was trying to use EntityUtils.toString(response) but it doesn't work.
This is my code:
public class Client {
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://countryapi.gear.host/v1/Country/getCountries?pName=Australia");
request.addHeader("accept", "application/json");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line = reader.readLine();
System.out.println(line);
}
}
The code actually return JSON for Australia, like this:
enter image description here
Try something like this:
Gson gson = new Gson();
JsonObject result = gson.fromJson(line, JsonObject.class);
JsonArray response = result.getAsJsonArray("Response");
Country country = gson.fromJson(response, Country.class);
You can use java api for json parsing. I am just writing a sample code. YOu can explore json parsing api more on below URL:
http://www.oracle.com/technetwork/articles/java/json-1973242.html
JsonObject obj = rdr.readObject();
JsonArray results = obj.getJsonArray("data");
for (JsonObject result : results.getValuesAs(JsonObject.class)) {
System.out.print(result.getJsonObject("name").getString("name"));
System.out.print(": ");
System.out.println(result.getString("message", ""));
System.out.println("-----------");
}

Parsing JSON Object from a JSON array

I am currently developing an app and need to parse JSON objects from inside an unnamed array.
I can only manage to parse JSON arrays with a name such as this one: http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt.
The code that I used for the one above is
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String asd = buffer.toString();
JSONObject parentObject = new JSONObject(asd);
JSONArray parentArray = parentObject.getJSONArray("movies");
JSONObject fObject = parentArray.getJSONObject(0);
String movie = fObject.getString("movie");
int year = fObject.getInt("year");
return movie + year;
The code includes "movies" which is the array name .
What should I change to parse only the objects from within a JSON array such as https://restcountries.eu/rest/v1/all?
Your countries list is simply an array. Doesn't need a name.
Simply replace
JSONObject parentObject = new JSONObject(asd);
with
JSONArray parentObject = new JSONArray(asd);
See this post for how to iterate over that array to parse the remainder of the objects.
How to parse JSON in Android
Starting something like
for (int i=0; i < parentObject.length(); i++) {
Alternatively, Volley's JsonArrayRequest would be useful, or learning about Retrofit+Gson would be even better if you don't feel like manually parsing the JSON data yourself.

String cannot be converted to JSON - Android

I have am trying to convert my response from a POST to JSON. And here is what I am doing:
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder response = new StringBuilder();
while((line = rd.readLine()) != null) {
response.append(line).append("\r");
}
rd.close();
Log.i(TAG, response.toString());
JSONObject jsonObject = new JSONObject(response.toString());
But then I get error java.lang.String cannot be converted to JSONObject
But if I make a string, String string; and then I paste the what I logged and set it equal to string, and then try
JSONObject jsonObject = new JSONObject(string);
It works, so why is it working when I paste the logged response, but not when I just use response.toString();?
In the logcat it looks like this {"url": "www.google.com"}. And then when I paste it into string = "{\"url\": \"www.google.com\"}";
Thanks for the help
I met this problem before, try this:
new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
or
if (response != null && response.startsWith("\ufeff")) {
in = in.substring(1);
}
the response from server contains a BOM header
public JSONObject(java.lang.String source)
throws JSONException
Construct a JSONObject from a source JSON text string.
source - A string beginning with { (left brace) and ending with } (right brace).
So while doing response.toString() if the string do not start with { and close with } then it will throw Exception.

How to read resulting JSON data into Java ?

I am trying to read results of a JSON request into java, yet
The partial output of my JSON request looks like this :
"route_summary": {
"total_distance": 740,
"total_time": 86,
"start_point": "Marienstraße",
"end_point": "Feldbergstraße"
}
I would like to use the standard json library to extract the values in total_distance.
However I only seem to be able to get the 'route_summary' by doing this :
JSONObject json = null;
json = readJsonFromUrl(request);
json.get("route_summary");
Where
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
What I want is get 'into' route_summary, any clue / tip would be great !
You need to get route_summary, as you already did, and from that object you need to get the total_distance. This will give you back the route_summary.total_distance.
Code sample:
JSONObject object = new JSONObject(s);
int totalDistance = object.getJSONObject("route_summary").getInt("total_distance");
I would recommend you to use GSON library. You can create class which will represent the message and then automatically map JSON to object by invoking function: gson.fromJson(message, YourMessageClass.class).getRoute_summary().
Here is the example of such approach: https://sites.google.com/site/gson/gson-user-guide/#TOC-Object-Examples

Categories