Converting String of Json to JsonObject - java

I have a String of Json received from a web service http get request. I would like to turn the string that I have formed into a JsonObject.
The question has been answered perfectly. Please see answer below.
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.util.List;
import java.io.*;
import java.util.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class RetrieveData {
public static String httpGet(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
public static void main(String[] args) {
try {
String jsonString = (httpGet("http://kinseyreporter.org/API/list/reports/?tag=male%20victim&from=2012-06-02"));
JsonObject obj = new JsonObject();
Gson gson = new Gson();
System.out.println(jsonString);
List<String> list = new ArrayList<String>();
gson.fromJson(jsonString, (Type) list);
String json = gson.toJson(jsonString);
System.out.println(json);
} catch (Exception E) {
}
}
}

For that, you need to parse your flux json, here the code.
JsonObject root = (JsonObject)new JsonParser().parse(jsonString);
int i=0;
JsonObject dataReports
//get and print each object of reports
while(root.getAsJsonObject().get("reports").getAsJsonArray().size()>i && (dataReports=root.getAsJsonObject().get("reports").getAsJsonArray().get(i).getAsJsonObject())!=null){
System.out.println(dataReports.toString());
i++;
}

Related

How to Split a JsonElement

So I was wondering how I could get an individual part of a JsonElement as when I run the program each element contains more information in it.
For example, it prints one of the elements in the JsonArray as [94372,1100000,1389792,31,43]
How would I be able to retrieve only the first number in the element?
import com.google.gson.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String inline = "";
try{
URL url = new URL("http://api.gw2tp.com/1/bulk/items.json");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responsecode = conn.getResponseCode();
if (responsecode!= 200)
throw new RuntimeException("HttpResponseCode: " +responsecode);
else {
Scanner sc = new Scanner(url.openStream());
while (sc.hasNext()){
inline+=sc.nextLine();
}
}
JsonParser parse = new JsonParser();
JsonObject jobj = (JsonObject)parse.parse(inline);
JsonElement updated = jobj.get("updated");
JsonArray jsonarr_1=(JsonArray)jobj.get("items");
JsonArray jsonarr_2=(JsonArray)jobj.get("columns");
System.out.println(jsonarr_2);
for(int i=0;i<jsonarr_1.size();i++) {
System.out.println(jsonarr_1.get(i));
}
}catch (Exception e){
e.printStackTrace();
}
}
}
That object is a JSONArray, calling .getAsJsonArray().get(0) will get its first entry:
System.out.println(jsonarr_1.get(0).getAsJsonArray().get(0));
outputs:
24
System.out.println(jsonarr_1.get(i).getAsJsonArray().get(0)); in your loop will output the first element of each array.
full code:
import com.google.gson.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String inline = "";
try{
URL url = new URL("http://api.gw2tp.com/1/bulk/items.json");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responsecode = conn.getResponseCode();
if (responsecode!= 200)
throw new RuntimeException("HttpResponseCode: " +responsecode);
else {
Scanner sc = new Scanner(url.openStream());
while (sc.hasNext()){
inline+=sc.nextLine();
}
}
JsonParser parse = new JsonParser();
JsonObject jobj = (JsonObject)parse.parse(inline);
JsonElement updated = jobj.get("updated");
JsonArray jsonarr_1=(JsonArray)jobj.get("items");
JsonArray jsonarr_2=(JsonArray)jobj.get("columns");
System.out.println(jsonarr_2);
for(int i=0;i<jsonarr_1.size();i++) {
System.out.println(jsonarr_1.get(i).getAsJsonArray().get(0));
}
}catch (Exception e){
e.printStackTrace();
}
}
}

Java - JSON - Return array of Objects within Object

Hey fellow overflow users,
I am having some issues wrapping my head fully around JSON calls in java.
I am using the JSON LIB located here:
http://www.java2s.com/Code/JarDownload/java-json/java-json.jar.zip
The JSON is currently structured as follows on the server end.
{
"patches":{
"patch1.zip":{
"name":"patch1.zip",
"type":"file",
"path":"patch1.zip",
"size":15445899,
"checksum":"ed4e2275ba67470d472c228a78df9897"
},
"patch2.zip":{
"name":"patch2.zip",
"type":"file",
"path":"patch2.zip",
"size":1802040,
"checksum":"59de97037e5398c5f0938ce49a3fa200"
},
"patch3.zip":{
"name":"patch3.zip",
"type":"file",
"path":"patch3.zip",
"size":6382378,
"checksum":"25efa1e9145a4777deaf589c5b28d9ad"
},
"user.cfg":{
"name":"user.cfg",
"type":"file",
"path":"user.cfg",
"size":819,
"checksum":"489a315ac832513f4581ed903ba2886e"
}
}
}
And below is what I currently have.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.HttpURLConnection;
import org.json.JSONException;
import org.json.JSONObject;
public class GetManifest {
public static void main(String[] args) throws IOException, JSONException {
try {
String url = "SEE ABOVE"; //My URL requires a username and password. Please see JSON Above.
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder response = new StringBuilder();
String line = "";
while((line = in.readLine()) != null) {
response.append(line).append(System.getProperty("line.separator"));
}
JSONObject responseJSON = new JSONObject(response.toString());
JSONObject loudScreaming = responseJSON.getJSONObject("patches");
System.out.println(loudScreaming);
} catch (MalformedURLException e) {
}
}
}
Please be easy with me, Java is not a language that I have really used before but I do have an okay understanding of its functions.
The issue I am having is that when I print the variable loudScreaming (yes I am losing my mind) I get all of the JSON with the nested data.
What I am actually trying to get is just the objects within patches to an array so I can then use the array to compare with a local copy and see if any of those file names are missing.
So in the end I am just trying to return the patches to an array without any of the nested data for now.
Answered by #AakashVerma in the comments. I have modified the code and you can see it working as below.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.HttpURLConnection;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class GetManifest {
public static void main(String[] args) throws IOException, JSONException {
try {
String url = "https://www.aerosimulations.com/wp-content/uploads/example.json";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder response = new StringBuilder();
String line = "";
while((line = in.readLine()) != null) {
response.append(line).append(System.getProperty("line.separator"));
}
JSONObject responseJSON = new JSONObject(response.toString());
JSONObject obj1_JSON = responseJSON.getJSONObject("patches");
System.out.println(obj1_JSON);
JSONArray patches = obj1_JSON.names();
System.out.println(patches);
} catch (MalformedURLException e) {
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.HttpURLConnection;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class GetManifest {
public static void main(String[] args) throws IOException, JSONException {
try {
String url = "https://www.aerosimulations.com/wp-content/uploads/example.json";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder response = new StringBuilder();
String line = "";
while((line = in.readLine()) != null) {
response.append(line).append(System.getProperty("line.separator"));
}
JSONObject responseJSON = new JSONObject(response.toString());
JSONObject obj1_JSON = responseJSON.getJSONObject("patches");
System.out.println(obj1_JSON);
JSONArray patches = obj1_JSON.names();
System.out.println(patches);
} catch (MalformedURLException e) {
}
}
}
See Above. used comments from user to complete.
[ ... ] - of this form is what indicates a JSON array. Edit your file like below
"patches":[
"patch1.zip":{
"name":"patch1.zip",
"type":"file",
"path":"patch1.zip",
"size":15445899,
"checksum":"ed4e2275ba67470d472c228a78df9897"
},
"patch2.zip":{
"name":"patch2.zip",
"type":"file",
"path":"patch2.zip",
"size":1802040,
"checksum":"59de97037e5398c5f0938ce49a3fa200"
},
"patch3.zip":{
"name":"patch3.zip",
"type":"file",
"path":"patch3.zip",
"size":6382378,
"checksum":"25efa1e9145a4777deaf589c5b28d9ad"
},
"user.cfg":{
"name":"user.cfg",
"type":"file",
"path":"user.cfg",
"size":819,
"checksum":"489a315ac832513f4581ed903ba2886e"
}
]
Try running your lines after changing like this.
If it doesn't work, try this below
FileReader file = new FileReader("patches.json"); //considering patches.json your file name
Object obj = parser.parse(file);
JSONObject jsonObject = (JSONObject) obj;
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
Object key = keys.next();
JSONObject value = jsonObject.getJSONObject((String) key);
String component = value.getString("component");
System.out.println(component);
}
Iterate through the properties of an JSONObject using keys()

Converting JSONObject to JSONArray Exception

I have a website that I have to make queries on in Java. Here you can see the dataset
https://www.quandl.com/api/v3/datasets/SSE/HYQ.json?start_date=2017-01-01&end_date=2017-01-31
At the very first beginning, I thought this is a JSONArray, but Eclipse always told me, it is not.
So therefore I tried to convert from JSONObject to JSONArray but I get this error:
org.json.JSONException: JSONObject["dataset"] is not a JSONArray.
What am I doing wrong?
Here is my code:
package query;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.*;
import java.io.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Stockquery {
public static void main(String[] args) {
String jsonString = callURL(
"https://www.quandl.com/api/v3/datasets/SSE/HYQ.json?start_date=2017-01-01&end_date=2017-01-31");
// System.out.println("\n\njsonString: " + jsonString);
try {
JSONObject jsonobjects = new JSONObject(jsonString);
System.out.println("\n\njsonArray: " + jsonobjects);
JSONArray arr = jsonobjects.getJSONArray("dataset");
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
System.out.println(obj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public static String callURL(String myURL) {
// System.out.println("Requested URL:" + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try {
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null)
urlConn.setReadTimeout(60 * 1000);
if (urlConn != null && urlConn.getInputStream() != null) {
in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null) {
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
} catch (Exception e) {
throw new RuntimeException("Exception while calling URL:" + myURL, e);
}
return sb.toString();
}
}
The dataset field of jsonobjects is a JSONObject not JSONArray. Change this:
jsonobjects.getJSONArray("dataset");
to this:
JSONObject dataset = jsonobjects.getJSONObject("dataset");
JSONArray array = dataset.getJSONArray("data");

JSON reads me only objects, no arrays

I'm using Eclipse, for an application where I have to read a JSON file from an URL.
The code I'm using is this one:
http://collegewires.com/android/2012/06/json-parsing-in-android/
Ok, the CLASS which I'm using for reading JSON files is called Parser.java:
package com.cw.json;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
public class Parser {
static InputStream is = null;
static JSONObject jsonObject = null;
static String json = "";
// class constructor
public Parser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException exception) {
exception.printStackTrace();
} catch (ClientProtocolException exception) {
exception.printStackTrace();
} catch (IOException exception) {
exception.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sBuilder.append(line + "\n");
}
is.close();
json = sBuilder.toString();
} catch (Exception exception) {
exception.printStackTrace();
}
// Parsing the string to a JSON object
try {
jsonObject = new JSONObject(json);
} catch (JSONException exception) {
exception.printStackTrace();
}
// JSON String
return jsonObject;
}
}
I was using this code for reading a JSON file which is directly an ARRAY, but the code gives me an error.
My question is: is it possible to read an Array instead always reading an Object??
maybe using another class?
Try to modify your Parser.java to this, so you gat a Array not a Object. And please buy you a JAVA Book for beginners, so you do learn how to speak JAVA
public JSONArray getJSONFromUrl(String url) {
....
static JSONArray jsonArray = null;
....
// Parsing the string to a JSON Array
try {
jsonArray = new JSONArray(json);
} catch (JSONException exception) {
exception.printStackTrace();
}
return jsonArray;
}

I want to view "source code" of the response generated from HTTP request in Java

My code can only return response status message or status code, but I need my code to return response in "view source" format i.e. in XML format :
import java.io.IOException;
import java.net.URL;
import java.net.HttpURLConnection;
public class API{
public static void main(String args[]) throws IOException
{
URL url = new URL("http://example.com");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
String statusCode = http.getResponseMessage();
System.out.println(statusCode);
}
}
You have to get stream and then read it. Like this:
import java.io.IOException;
import java.net.URL;
import java.net.HttpURLConnection;
public class API{
public static void main(String args[]) throws IOException
{
URL url = new URL("http://example.com");
HttpURLConnection http = (HttpURLConnection)url.openConnection();
String statusCode = http.getResponseMessage();
System.out.println(statusCode);
//read the result from the server
BufferedReader rd = new BufferedReader(new InputStreamReader(http.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = rd.readLine()) != null)
{
sb.append(line);
}
System.out.println(sb.toString());
}
}

Categories

Resources