Download JSON from URL(java) - java

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());
}

Related

Get last element of an array

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

Run js file in mongo using spring data

I am trying to run js file using mongo-template.
See StackOverFlow thread here
I am trying to use same code base, no change at all.
This does not work for me.
I get Exception at this line:
scriptOps.register(new NamedMongoScript("echo", echoScript));
Error:
org.springframework.core.convert.ConverterNotFoundException: No
converter found capable of converting from type
[org.springframework.data.mongodb.core.script.NamedMongoScript] to
type [com.mongodb.DBObject]
Complete StackTrace ...
org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:313)
at
org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:195)
at
org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:176)
at
org.springframework.data.mongodb.core.convert.MappingMongoConverter.writeInternal(MappingMongoConverter.java:375)
at
try{
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(new File("C:\\piyush\\t.js")));
try {
while (true) {
String line = br.readLine();
if (line == null)
break;
text.append(line).append("\n");
}
} finally {
try { br.close(); } catch (Exception ignore) {
System.out.println(ignore);
}
}
ExecutableMongoScript echoScript = new ExecutableMongoScript(text.toString());
Object ob=mongoOperation.scriptOps().execute(echoScript, "hello");
System.out.println(ob);
t.js
function(x) { return x; }
it will print hello

Get Json with i.e 200 objects, but only 100 displayd on one site

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.

Extracting array from response string

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"));
}

How to optimize android code

public String getBrotherHood() throws Exception{
client = new DefaultHttpClient();
get = new HttpGet(uri);
res = client.execute(get);
sl = res.getStatusLine();
sCode = sl.getStatusCode();
if(sCode==200)
{
try{
reader = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
readBuffer = new StringBuffer();
while((nl = reader.readLine())!=null){
readBuffer.append(nl);
}
reader.close();
}finally{
if(reader !=null)
{
try{
reader.close();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
return readBuffer.toString();
}
}
I have this code, is this the proper way of writing it, or should i need to follow any coding pattern or standards ??
Please give me some suggestions coz im not to Android Coding.
Update:
public class JSONData {
public ArrayList<String> getBrotherHoodJSON() throws JSONException,IOException,Exception{
ArrayList<String> item = new ArrayList<String>();
JSONArray jA = new JSONArray(getBrotherHood());
for(int i=0; i<jA.length(); i++)
{
JSONObject jO = jA.getJSONObject(i);
String n = jO.getString("name");
item.add(n);
Log.i("JsonData:",jO.getString("name"));
}
return item;
}
public String getBrotherHood() throws Exception{
BufferedReader in = null;
String data= null;
HttpClient client = new DefaultHttpClient();
URI uri = new URI("http://fahidmohammad.in/demo/Android/api.php?user=fah");
HttpGet get = new HttpGet();
get.setURI(uri);
HttpResponse res = client.execute(get);
StatusLine sl = res.getStatusLine();
int sCode = sl.getStatusCode();
if(sCode==200)
{
try{
in = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
StringBuffer sb = new StringBuffer();
String nl;
while((nl = in.readLine())!=null){
sb.append(nl);
}
in.close();
data = sb.toString();
Log.i("Raw Data:",data);
return data;
}finally{
if(in !=null)
{
try{
in.close();
return data;
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
return data;
}
Here is the updated version the same code.
Taken care of all the mentioned issues.
And also its working like a charm, but don't know the stability of it.
You obviously have declared all variables outside your method even though they seem to be used only within this method. That makes no sense. It prevents several objects from being garbage collected. You better move the declaration into the method.
And the declaration throws Exception doesn't make much sense either. You are better of if you either declare a specific exception that could likely occur or if you convert all unlikely exceptions into RuntimeException so you don't need to declare them.
There is a default code formatter is available eclipse. after wrote your code just type "Control + Shift + F". Your android code will formatting automatically.
one more important point regrading readBuffer varible
At the last of the function you are returning readBuffer.toString() and you initialized this only when status in 200. But if status in not 200 then it would be null (assuming as declaration is not visible ) so null.toString() will thought exception.

Categories