This is not a duplicate
My JSON is not in an JSONArray, My JSON is all objects. However I have passed the objects into an JSONArray as it was the only way I could figure out how to get each objects in 'patches'.
Right now I have everything converted to a JSONArray but I am unable to use it like I would like. The end goal of this is to take the JSON from the server end (Which is dynamic by the way, the patch files under patches get regenerated and new patches are added) Eventually I want to take that array list and use it to search for those packages in the users directory, but thats for later.
Right now I can't figure out how to convert data out of the JSONArray.
The JSON is currently structured as follows on the server end. (This structure CANNOT BE CHANGED).
{
"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"
}
}
}
I have looked into using GSON and JACKSON but can't figure out how to make them work when pulling out dynamic data from JSON.
I am using the org.json LIB.
ReadUrl.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class ReadUrl {
static String getUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuilder buffer = new StringBuilder();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
}
Main.java
import org.json.JSONArray;
import org.json.JSONObject;
public class Main {
private static final boolean isDebugMode = true;
/**
* @param args the command line arguments
* @throws java.lang.Exception
*/
public static void main(String[] args) throws Exception {
String sReadURL = ReadUrl.getUrl("http://www.aerosimulations.com/wp-content/uploads/example.json");
if (isDebugMode) {
System.out.println(sReadURL);
}
JSONObject responseJSON = new JSONObject(sReadURL);
JSONObject obj1_JSON = responseJSON.getJSONObject("patches");
JSONArray jPatches = obj1_JSON.names();
if (isDebugMode) {
System.out.println(jPatches);
}
for(int i = 0; i < jPatches.length(); i++){
}
}
}
My requirement is, I need to be able to get the patch names from 'patches' and return a usable java array.