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.
Related
I'm trying to parse multiple objects from a REST response. They initially get returned as JSON Lines (jsonl file format). i.e.:
{"AccountId":"123","Name":"Jeff"}
{"AccountId":"456","Name":"Joe"}
{"AccountId":"789","Name":"John"}
The first thing I do is convert it to a string:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.com", 8080));
HttpsURLConnection httpsCon = (HttpsURLConnection) (new URL(url)).openConnection(proxy);
InputStream inputStream = httpsCon.getInputStream();
Reader reader = new InputStreamReader(inputStream);
char[] arr = new char[8 * 1024];
StringBuilder buffer = new StringBuilder();
int numCharsRead;
while ((numCharsRead = reader.read(arr, 0, arr.length)) != -1) {
buffer.append(arr, 0, numCharsRead);
}
reader.close();
return buffer.toString();
But I get errors trying to parse the String it as it's not JSON structure. So I've used a regex to format the objects into JSON structure.
{"AccountId":"123","Name":"Jeff"},{"AccountId":"456","Name":"Joe"},{"AccountId":"789","Name":"John"}
What I've tried so far:
JSONArray dataArr = new JSONArray(newTargetString);
Results in: type org.json.JSONObject cannot be converted to JSONArray
JSONObject dataObj = new JSONObject(newTargetString);
Results in a single object getting parsed instead of all 3.
This has probably been asked before, but I do not know the terminology for my question, therefore do not know what to look up.
I am using GSON and Java trying to get information from a parsed JSONElement.
Java code:
JsonParser parser = new JsonParser();
String url = "https://chapel-logs.herokuapp.com/attendance";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("Accept", "application/json");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
JsonElement element = parser.parse(response.toString());
if (element.isJsonObject()) {
JsonObject albums = element.getAsJsonObject();
System.out.println(albums.get("students")); //prints out data in students
System.out.println(albums.get("students.LastChapelAttended")); //error
}
My JSON :
{"students":[{"LastChapelAttended":{"Loc":"","Chapel":"WhyChapel","Year":2018,"Month":9,"Day":6,"Hour":15,"Min":14,"Sec":28},"StudNum":"F02660934","Attendance":17},{"LastChapelAttended":{"Loc":"","Chapel":"WhyChapel","Year":2018,"Month":9,"Day":5,"Hour":19,"Min":49,"Sec":11},"StudNum":"002660934","Attendance":2},{"LastChapelAttended":{"Loc":"","Chapel":"WhyChapel","Year":2018,"Month":9,"Day":4,"Hour":20,"Min":35,"Sec":57},"StudNum":"002643472","Attendance":2},{"LastChapelAttended":{"Loc":"","Chapel":"WhyChapel","Year":2018,"Month":9,"Day":7,"Hour":5,"Min":34,"Sec":54},"StudNum":"002664906","Attendance":1}]}
The data I am trying to get is: LastChapelAttended, however LastChapelAttended is within students. In JavaScript the equivalent to what I am trying would be students.LastChapelAttended if that helps.
Thanks in advance!
JsonObject jObj=(JsonObject)albums.get("students").getAsJsonArray().get(0);
System.out.println(jObj.get("LastChapelAttended"));
Get it as a JsonArray and then loop through the array to get LastChapelAttended.
First, students is not an object but an array. Thus students.LastChapelAttended should not work in any language. If you want to retrieve LastChapelAttended of the first student in the array students[0].LastChapelAttended should work.
I am not familiar with gson, but I think what you want to do is something like this:
if (element.isJsonObject()) {
JsonObject albums = element.getAsJsonObject();
JsonArray students = albums.getAsJsonArray("students");
for (JsonElement student : students) {
System.out.println(albums.getAsJsonObject().get("LastChapelAttended"));
}
}
You can check this out for help Difference between JSONObject and JSONArray
Students is a JsonArray
LastChapelAttended is a JSONObject you can get it by calling
json = (json data)
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonArray studentsArray = rootObj.getAsJsonArray("students");
for (JsonElement stu : studentsArray) {
JsonObject student = stu.getAsJsonObject();
JsonObject LastChapelAttended = student.getAsJsonObject("LastChapelAttended");
}
Just iterate over the student array
albums.getAsJsonArray("students")
.forEach(student -> System.out.println(student.getAsJsonObject()
.get("LastChapelAttended")));
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();
}
I have a URL that retuns a JSON back and I first convert it to String and then convert it to JSONArray but for some reason, it's returning null.
The sample url looks like this:
https://data.phila.gov/resource/sspu-uyfa.json?dispatch_date=2017-08-01
Below is my code:
public JSONArray getJsonFromUrl(final String data_url) throws IOException, JSONException {
InputStream is = new URL(data_url).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
is.close();
JSONArray jsonArray = new JSONArray(sb.toString());
return jsonArray;
}
So the StringBuilder object sb is not null. When I debug, I can see it is a huge string. But it's new JSON(sb.toString()); that returns null. Also, I tried replacing JSONArray with JSONObject and still same issue.
Any help would be appreciated!
your data has a SyntaxError. in near column 48697,
H have find the bad data segment:
,"ucr_gen1447C3FA9C2915241",
I think you would like :
,"ucr_general":"1447C3FA9C2915241",
I am trying to send a request to the Grooveshark API using POST Payload and their requested methods, and I have found a problem. Allow me to show you my code first.
public void getResponse() throws Exception
{
if(service.equals("Grooveshark")) link += getHmacMD5(privateGroovesharkKey, jsonInfo.toString());
if(requestedMethod.equals("GET")) infoURL = new URL(link+arguments);
else infoURL = new URL(link);
HttpURLConnection connection = (HttpURLConnection) infoURL.openConnection();
connection.setRequestMethod(requestedMethod);
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
if(service.equals("Grooveshark"))
{
connection.setRequestProperty("Content-Type","application/json");
OutputStream output = connection.getOutputStream();
output.write(jsonInfo.toString().getBytes());
}
else if(requestedMethod.equals("POST") || requestedMethod.equals("PUT"))
{
OutputStream output = connection.getOutputStream();
output.write(arguments.getBytes());
}
connection.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null)
sb.append(line).append('\n');
setJsonResult(sb.toString());
System.out.println(jsonResult);
jsonFinal = new JSONObject(jsonResult);
connection.disconnect();
}
I have got that code up here in my project, and I can successfully send requested to any API Webservice that uses JSON in their responses. Now there's only a problem: In Android, it does not give me the WHOLE answer. I've tried running the code on a separate Java (no Android) project, and I get the following output. Although, if I run it on Android, the Log shows me the following:
{"header":{"hostname":"RHL073"},"result":{"songs":[{"SongID":5443351,"SongName":"??????\u00b7???? (FINAL FANTASY XII????)","ArtistID":713,"ArtistName":"Final Fantasy","AlbumID":898007,"AlbumName":"Final Fantasy XII Original Soundtrack","CoverArtFilename":"","Popularity":1214500005,"IsLowBitrateAvailable":tr
And it stops on that tr. Has it anything to do with the parsing of the file that I actually apply afterwards? I don't think it is, but just in case, here it is [This is how I call the search, JSONHandler being the object that contains the code provided above]:
public void performSearch() throws Exception
{
JSONObject search = new JSONObject();
search.put("method", method);
JSONObject header = new JSONObject();
header.put("wsKey", key);
JSONObject parameters = new JSONObject();
parameters.put("query", getSearchQuery());
parameters.put("country", "Portugal");
parameters.put("limit", limit);
parameters.put("offset", "");
search.put("header", header);
search.put("parameters", parameters);
JSONHandler jsonHandler = new JSONHandler(link, search, "Grooveshark", "POST", "");
JSONObject finalResult = jsonHandler.getJsonFinal();
JSONArray songs = finalResult.getJSONObject("result").getJSONArray("songs");
ArrayList<Result> allResults = new ArrayList<Result>();
for(int i = 0; i < songs.length(); i++)
{
JSONObject inner = (JSONObject) songs.get(i);
String name = inner.getString("SongName");
int ID = inner.getInt("SongID");
String artist = inner.getString("ArtistName");
Result res = new Result(name, artist, ID);
res.setAlbumName(inner.getString("AlbumName"));
boolean low = inner.getBoolean("IsLowBitrateAvailable");
int bit = 0;
if(low) bit = 1;
else bit = 0;
res.setIsLowBitRateAvailable(bit);
}
setResults(allResults);
}
As you can clearly see, I am using the json.org library. I really don't understand what's the problem here. Has anyone got any idea as to why?