I have a response like below from node how do I extract it to be as array in java
[
{
"userName":"Steve",
"date":"Tue Aug 13 18:44:23 GMT+05:30 2013",
"message":"Good morning sir."
}
]
Note : finally did it guys, sorry for wasting you guys time, see my last comment :)
i'm making an http request to server written node, and in server i'm sending an array of objects [{}, {}, ...] back to java,
now coming to java, i'll read the response using InputStream and constructing the result String.
and i'm getting the string like specified above, what i want is like how to convert the string to array so that i can loop and access the objects in the array
HttpGet httpget = new HttpGet('some uri');
HttpEntity httpentity = httpclient.execute(httpget).getEntity();
private void renderResponseAndQueueResults(HttpEntity httpentity) {
try {
InputStream is = httpentity.getContent();
String result = convertStreamToString(is);
is.close();
appendResultToMap(result);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while( (line = reader.readLine()) != null){
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try{
is.close();
}catch (IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
the return of the convertStreamToString is an String like
[
{
"userName":"Steve",
"date":"Tue Aug 13 18:44:23 GMT+05:30 2013",
"message":"Good morning sir."
}
]
now how can i loop through it
You need to refer to the JSON library APIs: http://www.json.org/javadoc/org/json/JSONArray.html.
This may be something you want:
//process the JSON array parsed out from the source string
for (int i = 0; i < arr .length(); i++)
{
//get each JSON object of the array
JSONObject iObj = arr.getJSONObject(i);
//access the content of the JSON object, like print it
System.out.println(iObj.getString("userName"));
}
Related
through an API I get an array with a lot of different data. But I only need the last element.
The variable sb has the array in it. But i cannot access elements like that: sb[0] (for example)
If I print the variable sb it looks like that:
{"data":[[[1583596801195,279.52],[1583596814340,279.52],[1583596815535,279.44563849372383],[1583596816730,279.2060000000001],[1583596913525,279.2060000000001],[1583596914720,279.28824435146447],[1583596915915,279.52],[1583597211080,279.52],[1583597212275,279.52000000000004],[1583597213470,279.52],[1583597609015,279.52],[1583597610210,279.5199999999999],[1583597707005,279.5199999999999],[1583597708200,279.52000000000004],[1583597709395,279.52],[1583597806190,279.52],[1583597807385,279.52000000000004],[1583597993805,279.52000000000004]]]}
In this case, I only need the last element (279.52000000000004).
My code look like that:
URL url = new URL("the URL i get the data from");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
InputStream instream = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(sb);
Sorry I am not experienced that experienced with programming. But I would really appreciate if someone could help me.
Thank you for your help.
If you need the last element only, you should not be appending the results.
Instead, replace the previous value stored.
String result = null;
String line = null;
try {
while ((line = reader.readLine()) != null) {
//sb.append(line + "\n");
result = line; // not appending, but replacing
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(result);
You can try this, replace this line "System.out.println(sb) with below code :
String s = new String(sb);
String d[] = s.split(",");
System.out.println(d[d.length -1].replaceAll("]", ""));
This would print the exact data you want i.e 279.52000000000004
I extracted a huge String from a webpage and want to style/formatting this in Json style. The extracted String was originally a Json format but now after extracting this is just a long String. I used JsonObj for this and the formatter does curios things, he moved text from the bottom to top changed the generally the line orders etc.
http://pastebin.com/exwwc6SY JsonFile after Formatting
http://pastebin.com/WHXtE36G The extracted String
And here the code
try {
FileWriter fw = new FileWriter("/tmp/1.txt");
String line = ROUtils.getStringFromInputStream(urlConnection.getInputStream());
System.out.println(line);
String jsonObj = new JSONObject(line).toString(2);
fw.write(jsonObj);
} catch (IOException e) {
e.printStackTrace();
}
And the getStringFromInputStream() method
public static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
return sb.toString();
}
Update
I found a new issue. The JsonObj File its not equal to the original String.
I compared the number of Characters (no spaces). The original String has 96311 and the JsonObj has 92636. Can anyone give me a hint what should I do?
You cannot and should not rely on the ordering of elements within a JSON object.
From the JSON specification at http://www.json.org/
An object is an unordered set of name/value pairs.
I found it out why i missed 4000 characters after converting.
I forgot to close the FileWriter!
fw.close();
The close() methods calls the flush() method so that the last buffered piece of the String can written down.
Thank u guys.
Good evening, I'm sorry for my english. I want to try to deduce, using a link from json in the console. Sometimes is used json-simple-1.1.1.jar. I do not understand what the problem is, writes
Exception in thread "main" java.lang.NullPointerException at
kkkkkkkkkkkk.main.main (main.java:34)
private static final String filePath = "http://ksupulse.tk/get_all.php";
public static void main(String[] args) throws org.json.simple.parser.ParseException {
try {
URL serverAddress = new URL(filePath);
HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
connection.connect();
int rc = connection.getResponseCode();
if(rc == 200) {
String line = null;
BufferedReader reader = new BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
while((line = reader.readLine()) != null)
sb.append(line + '\n');
JSONObject obj = (JSONObject) JSONValue.parse(sb.toString());
//error
JSONArray array = (JSONArray) obj.get("response"); //<-------err this line
for(int i = 0; i < array.size(); i++) {
JSONObject list = (JSONObject) ((JSONObject)array.get(i)).get("list");
System.out.println(list.get("id")+": "+list.get("name"));
}
} else {
System.out.println("Connect error");
}
connection.disconnect();
} catch (java.net.MalformedURLException e) {
e.printStackTrace();
} catch (java.net.ProtocolException e) {
e.printStackTrace();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
Can u provide the json text ?This is happening due to improper parsing of json text. The error is "Null Pointer Exception" . These types of error occur when you try to access some undefined resource . A good way to debug this one is to use a general exception and try to find the exact error . Your code is only handling 3 errors .You need to handle other errors also. Try using this.
try{
//Some code
}(Exception e){
System.out.println("Error:"+e.toString());
}
I'm working in my Twitch IRC Bot and we got a Problem.
We receive alot of information through the twitch API (json) like Who followed, dateOf .. viewercounts.. amount of followers and stuff like that.
Were making a Follow-Function to read all the names out of the whole list and set all into our database. First off we tried to just read all and system.output them but we always get the error: org.json.JSONException: JSONArray[100] not found.
We noticed that "0" is holding an array as well so we set the loop to 0-99 and it should change the link then by adding 100+ (next site) and read the JSON again. then it should just continue the loop with the next site.
Below is the Main code as well for the read-methods.
We tried debugging but we wasn't able to find a solution yet x(
MyBot Main Code Snippet:
JSONObject follower = null;
String followername = null;
int listnumber;
offsetvalue = 0;
for(int i = 0; i < TwitchStatus.totalfollows; i++) {
try {
follower = TwitchStatus.followerarray.getJSONObject(i);
} catch (JSONException e2) {
e2.printStackTrace();
}
try {
followername = follower.getJSONObject("user").getString("display_name");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("array ist: "+i +" " +followername);
listnumber = offsetvalue+99; // 0+99
if (i == listnumber){
offsetvalue = offsetvalue+100;
try {
TwitchStatus.FollowerTicker();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
// System.out.println("Follower abgleichs-Liste: "+followername);
}
And there is the Reader Method:
////////////////////////////////////////////////////////////////////////////////////
// Twitch Follower Ticker
////////////////////////////////////////////////////////////////////////////////////
private String readAll4(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public JSONObject readJsonFromUrl4(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 = readAll4(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void FollowerTicker() throws IOException, JSONException {
json = readJsonFromUrl2("https://api.twitch.tv/kraken/channels/dotastarladder_en/follows?direction=DESC&limit=100&offset="+MyBot.offsetvalue+"");
followerarray = json.getJSONArray("follows");
{
JSONObject follower = followerarray.getJSONObject(0);
neuerfollower = follower.getString("created_at");
fname = follower.getJSONObject("user").getString("display_name");
totalfollows = json.getInt("_total");
}
}
Note from the API docs:
limit optional integer Maximum number of objects in array. Default is 25. Maximum is 100.
So, what do you do? Query the next one, of course! Here's the bit of JSON from the linked page, and an example next URL. Basically, you just put an offset in, but the URL already declares it, so...
{
"_total": 1234,
"_links": {
"next": "https://api.twitch.tv/kraken/channels/test_user1/follows?direction=DESC&limit=25&offset=25",
How I would solve this problem is something like this:
Create an AsyncTask that takes in the URL to parse the JSON text.
When the data has been received, start a new task to read the next one.
Read everything received in this JSON string
Compile everything after it has been downloaded as needed.
I'm reading a JSON file in my android project, just to see the first position of the array.
In fact, if this JSON is more big what normal, I think this isn't efficient...
My json file reader:
public static JSONObject parseJSONfromInputStrem (InputStreamReader isr){
try {
BufferedReader reader = new BufferedReader(isr,8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
Where I call the function:
FileInputStream fis = c.openFileInput(file);
InputStreamReader isr = new InputStreamReader(fis);
JSONObject jso = JSONParser.parseJSONfromInputStrem(isr);
JSONArray myArray = jso.getJSONArray("data");
There are any way to read, efficiently, the first position of a JSONArray?
You should use a streaming JSON parser (think DOM vs SAX).
https://stackoverflow.com/a/823632/18573 lists some. There may be others.
You can either read in a small amount of the file and pull the value out manually, or put the value in to a separate file. Even if it's duplicated data, a secondary file which contains summarized or key information from the primary file will make things much more efficient.