Use getJSONObject(int) - java

I'm trying to parse some JSON. Here is the code. frc-manual.usfirst.org/a/GetAllItems/ManualID=3 I have been trying for several hours to get it work but every example I have seen online uses getJSONObject(int) but I can only use getJSONObject(String). This is making impossible. Am I overlooking something?
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.annotation.SuppressLint;
public class JSON {
private String html = "html";
private String version = "version";
private String pageString = null;
private String urlString = "http://frc-manual.usfirst.org/a/GetAllItems/ManualID=3";
public volatile boolean parsingComplete = true;
public JSON(String page){
this.pageString = page;
}
public String getHTML(){
return html;
}
public String getVersion(){
return version;
}
#SuppressLint("NewApi")
public void readAndParseJSON(String in) {
try {
JSONObject reader = new JSONObject(in);
JSONObject head = reader.getJSONObject("data").getJSONObject("SubChapter").getJSONObject("3").getJSONObject("children").getJSONObject(pageString);
if(head != null){
html = head.getString("item_content_text");
html = html + head.length();
for(int i = 0; i < head.length();i++){
JSONObject children = head.getJSONObject(i);
if(children != null){
html = html + children.getString("item_content_text");
}
}
}
//html = html + listFromJsonSorted(head.getJSONObject("children"));
JSONObject main = reader.getJSONObject("data");
version = main.getString("LatestManualUpdate");
parsingComplete = false;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void fetchJSON(){
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
String data = convertStreamToString(stream);
readAndParseJSON(data);
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}

Probably what you are seeing in this example is a JSONArray.
JSONArray arr = json.getJSONArray("array");
JSONObject obj = arr.getJSONObject(0);
In your case, i don't see any array in this JSON, head in your code is a JSONObject. To get the item_content_text you just need head.getString("item_content_text");
You can do this to get all childrens in your JSON:
html = head.getString("item_content_text");
JSONObject children = head;
while (children.containsKey("children")) {
children = children.getJSONObject("children");
html += children.getString("item_content_text");
}

You are only able to use getJSONObject(String) not getJSONObject(int) because the method only takes String.. Check documentation here..
The reason that is the because the keys in json are always strings only.. read here
I think you are looking to retrieve an int value from the json but you got confused.. The way to do that would be getInt("key_name") if the json indeed has a key with int value..

Sure you can, just that I think your "head" variable should have a return type of JSONArray instead of JSONObject.
I have this code running in my program -
//response = some http response
final JSONObject object = new JSONObject(response);
final JSONArray array = object.getJSONArray("repeatedStuff"); //$NON-NLS-1$
Assert.assertEquals(2, array.length());
for (int i = 0; i < array.length(); i++) {
final JSONObject element = array.getJSONObject(i);
//do something
}
Also you may refer this link to see what they are doing - android: The method getJSONObject(int) in the type JSONArray is not applicable for the arguments (String)
Let me know if that helped!

You have used JSONObject everywhere in your code. Thus you are only able to pass string parameter in getJSONObject().
I suggest you you change it to JSONArray and then you will be able to pass int parameter in getJSONObject().

Related

Json data fetching lag problem from jsonbin.io

I'm working on a app that is a simple game, so here's a picture for the UI I have, the problem is when I fetch a level using Json web service, the first time I choose the level from activity_level_list, the picture and level number doesn't show, only the 4 words works but neither the image nor the level number appear like this.
NOTE: The image URL variable is null (because of the lag that happens the first time I open first level activity) so an error happen (that's why it shows ic_launcher instead of showing the level picture).
So, I said the problem was "lag" because when I go back to LevelList and click on level 1, the picture and the level number get fetched and everything becomes good.
How can I make it both the image and level ID appears in the first time I open the activity?
NOTE: I use jsonbin.io for data fetching.
Here's my Json data fetching class:
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FetchData extends AsyncTask<Void,Void,Void> {
String update = "4";
String data ="";
String id;
String img;
String w1;
String w2;
String w3;
String w4;
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://api.jsonbin.io/b/5e42776dd18e4016617690ce/" + update);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
// for(int i = 0 ;i < JA.length(); i++) {
JSONObject JO = (JSONObject) JA.get(1);
id = (String) JO.get("id");
img = (String) JO.get("img");
w1 = (String) JO.get("w1");
w2 = (String) JO.get("w2");
w3 = (String) JO.get("w3");
w4 = (String) JO.get("w4");
// }
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
int levelId = Integer.parseInt(id);
levelId++;
LevelActivity.levelID = String.valueOf(levelId);
LevelActivity.imageURL = img;
LevelActivity.button1Word = w1;
LevelActivity.button2Word = w2;
LevelActivity.button3Word = w3;
LevelActivity.button4Word = w4;
}
}
Thanks ^-^
I just needed to update the image and level text view number in onPostExecute method to make it load from the first time.
Answer by NIKHIL AGGARWAL

Splitting String into object fields

I looking for best aproach for this problem.
String example:
{"id":16,"title":"title1","description":"Quote \"foo\" asdf","execution_time":"2017-04-26 06:15:00"}
I need to create new object with gets fields values from the string. What is correct way to do it? Creating constructor and pass this string as parameter and use stringtokenizer inside it? Or maybe using Pattern would be better?
(I am going to correct the code)
I am proposing to use org.json.simple.*. In my opinion, it will be easy, for example:
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
public class ParseJson1 {
public static void main(String[] args) {
String url = "....";
/*
* {"id":16,"title":"title1","description":"Quote \"foo\" asdf","execution_time":"2017-04-26 06:15:00"}
*/
try {
String genreJson = IOUtils.toString(new URL(url));
JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
// get the title
System.out.println(genreJsonObject.get("title"));
// get the data
JSONArray genreArray = (JSONArray) genreJsonObject.get("dataset");
// get the first genre
JSONObject firstGenre = (JSONObject) genreArray.get(0);
System.out.println(firstGenre.get("genre_title"));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}

Reading a json file in Java

So I am having troubles with reading a Json file in Java.
It is a Json file with content in this format:
{
"_id": 2864071,
"name": "Neustadt",
"country": "DE",
"coord": {
"lon": 12.56667,
"lat": 52.400002
}
}
This is the code I am using:
package controllers;
#Named(value = "cityID")
#SessionScoped
public class getCityIDs implements Serializable {
public long getCityIDs(String name) {
//Read the json file
try {
FileReader reader = new FileReader(filePath);
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(reader);
// get a number from the JSON object
String travelName = (String) jsonObject.get("name");
if(travelName.equals(name)){
long id = (long) jsonObject.get("_id");
System.out.println(id);
return id;
} else {
System.out.println("else");
return 0;
}
} catch (FileNotFoundException ex) {
Logger.getLogger(getCityIDs.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | ParseException ex) {
Logger.getLogger(getCityIDs.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("einde functie");
return 0;
// JSONObject jsonObject = (JSONObject) parser.parse(getClass().getResource("/json/city.list.json").toString());
}
public String test(){
return "hello world";
}
}
However, it gives me an error at this line:
JSONObject jsonObject = (JSONObject) parser.parse(reader);
being:
Severe: Unexpected token LEFT BRACE({) at position 88.
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at org.json.simple.parser.JSONParser.parse(Unknown Source)
at controllers.getCityIDs.getCityIDs(getCityIDs.java:45)
For some reason it can't read the filepath? "Unknown source"?
I'm not sure what I'm doing wrong.
The method just returns a "0" when I call the method in another class, with as country name "Neustadt".
Basically all I want is for this function to return the ID for a certain city.
The names are stored in the Json, together with the ID.
Edit:
Ideally I want to be able to parse the JSON file, which is located inside the project.
I tried using .getClass().getResource("/path/to/json"); but that didn't work at all.
EDIT: FIXED
package controllers;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
#Named(value = "cityID")
#SessionScoped
public class getCityIDs implements Serializable{
JSONObject jsonObject;
public long getCityIDs(String name) {
try {
JSONParser parser = new JSONParser();
InputStream in = getClass().getResourceAsStream("/dataSteden/stedenNamen1.json");
try (BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
String line;
while ((line = br.readLine()) != null) {
jsonObject = (JSONObject) parser.parse(line);
}
}
String travelName = (String) jsonObject.get("name");
System.out.println("stad: " +travelName);
System.out.println("testttt");
if(travelName.equals(name)){
long id = (long) jsonObject.get("_id");
System.out.println(id);
return id;
} else {
System.out.println("else");
return 5;
}
} catch (FileNotFoundException ex) {
Logger.getLogger(getCityIDs.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | ParseException ex) {
Logger.getLogger(getCityIDs.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("einde functie");
return 0;
// JSONObject jsonObject = (JSONObject) parser.parse(getClass().getResource("/json/city.list.json").toString());
}
public String test(){
return "hello world";
}
}
Your data is line-delimited
{"_id":707860,"name":"Hurzuf","country":"UA","coord":{"lon":34.283333,"lat":44.549999}}
{"_id":519188,"name":"Novinki","country":"RU","coord":{"lon":37.666668,"lat":55.683334}}
{"_id":1283378,"name":"Gorkhā","country":"NP","coord":{"lon":84.633331,"lat":28}}
Therefore, you cannot throw the entire file into a JSONParser, you must read the file line-by-line and parse each line as a JSONObject, from which you can extract out the needed key-values.

Deploy a .bpmn file via REST

i want to deploy a BPMN-file with the REST-API of Activiti. But i always get a Bad Request (400) error...
Has anybody an idea what i'm doing wrong??? I use restlet to upload my code. My code is below.
Thank your very much :)
import java.io.File;
import java.io.IOException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Disposition;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.representation.FileRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
public class REST {
private static String REST_URI = "http://localhost:8080/activiti-rest/service";
private static ClientResource getClientResource(String uri) {
ClientResource resource = new ClientResource(uri);
resource.setChallengeResponse(ChallengeScheme.HTTP_BASIC, "kermit", "kermit");
return resource;
}
public static JSONArray postDeployments() throws JSONException, IOException {
String deploymentURI = REST_URI + "/repository/deployments";
File file = new File("C:\\Users\\Test\\Desktop\\process.bpmn");
FileRepresentation fr = new FileRepresentation(file, MediaType.TEXT_PLAIN);
System.out.println("Size sent: " + fr.getSize());
try{
Representation response = getClientResource(deploymentURI).post(file, MediaType.MULTIPART_FORM_DATA);
JSONObject object = new JSONObject(response.getText());
if (object != null) {
JSONArray dataArray = (JSONArray) object.get("data");
return dataArray;
}
}
catch(Exception e){
System.out.println("Error:");
e.printStackTrace();
}
return null;
}
}
You are not generating the multipart-form-data request properly with Restlet.
You could have done the following to deploy a business process to activiti REST API:
String deploymentURI = REST_URI + "/repository/deployments";
File file = new File("/home/toto/fake-process.bpmn20.xml");
FileRepresentation entity = new FileRepresentation(file, MediaType.MULTIPART_FORM_DATA);
FormDataSet fds = new FormDataSet();
FormData fd = new FormData("upload_file", entity);
fds.getEntries().add(fd);
fds.setMultipart(true);
try {
Representation response = getClientResource(deploymentURI).post(fds);
} catch (Exception e) {
System.out.println("Error:");
e.printStackTrace();
}
See also this post

Parsing the web page response as Json, in Java

I have a java code:
URL oracle = new URL("https://x.x.x.x.x.x.-001");
System.out.println(oracle.openStream());
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
Which is opening the connection and printing the contents of it. The contents are indeed Json. The output is something like:
{
"merchantId": "guest",
"txnId": "guest-1349269250-001",
}
I wish to parse this in json simple jar. I changed the code loop like this:
JSONObject obj = new JSONObject();
while ((inputLine = in.readLine()) != null)
obj.put("Result",inputLine);
But that doesn't seem to be working. The output I'm getting is:
{"Result":"}"}
You should use the JSONParser#Parse() method or the JSONValue#parse() method :
URL oracle = new URL("https://x.x.x.x.x.x.-001");
System.out.println(oracle.openStream());
Reader in = new InputStreamReader(oracle.openStream());
Object json = JSONValue.parse(in);
Are you sure you're following the documentation on how to parse a JSON string?
By the looks of it you have to obtain the entire string and call a JSONParse#parse() on it, but your code is filling up a HashMap (JSONObject's parent class) with each of the lines of the JSON. In fact it stores just the last line because you're calling put() with the same "Result" key on every iteration.
You should read whole contents to String variable first and parse it to json. Be careful of ""(double quote). Java uses \" for double quote. Like.
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonSimpleExample3 {
public static void main(String args[]) {
JSONParser parser = new JSONParser();
//String str = "{\"merchantId\": \"guest\",\"txnId\": \"guest-1349269250-001\",}";
//intilize an InputStream
InputStream is = new ByteArrayInputStream("file content".getBytes());
//read it with BufferedReader and create string
BufferedReader br = new BufferedReader(new InputStreamReader(is));// Instead of is, you should use oracle.openStream()
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e1) {
e1.printStackTrace();
}
// parse string
try {
JSONObject jsonObject = (JSONObject) parser.parse(sb.toString());
String merchantId = (String) jsonObject.get("merchantId");
System.out.println(merchantId);
String txnId = (String) jsonObject.get("txnId");
System.out.println(txnId);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
try this link its really helpful if you are going to be logging in or staff like that
Java Json simple
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
public class ParseJson1 {
public static void main(String[] args) {
String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
/*
* {"title":"Free Music Archive - Genres","message":"","errors":[],"total" : "161","total_pages":81,"page":1,"limit":"2",
* "dataset":
* [{"genre_id": "1","genre_parent_id":"38","genre_title":"Avant-Garde" ,"genre_handle": "Avant-Garde","genre_color":"#006666"},
* {"genre_id":"2","genre_parent_id" :null,"genre_title":"International","genre_handle":"International","genre_color":"#CC3300"}]}
*/
try {
String genreJson = IOUtils.toString(new URL(url));
JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
// get the title
System.out.println(genreJsonObject.get("title"));
// get the data
JSONArray genreArray = (JSONArray) genreJsonObject.get("dataset");
// get the first genre
JSONObject firstGenre = (JSONObject) genreArray.get(0);
System.out.println(firstGenre.get("genre_title"));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}

Categories