Read JSON in Java from URL that starts with unnecessary data - java

I would like to process JSON data started with an object that I don't need.
Here you have the URL:
http://datos.santander.es/api/rest/datasets/callejero_calles.json?items=819
I have been trying to adapt next code, but I don't know how to avoid the first object (summary) and take the second one (resources).
If I want to take one by one all the data inside from each object of "resources" (for example, showing "nombre-calle", "tipo-via"...).
package leerjson;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class LeerJSON {
public static void main(String[] args) throws ParseException {
JSONParser parser = new JSONParser();
try {
URL oracle = new URL("http://datos.santander.es/api/rest/datasets/callejero_calles.json?items=819"); // URL to Parse
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
in.readLine();
while ((inputLine = in.readLine()) != null) {
JSONArray a = (JSONArray) parser.parse(inputLine);
// Loop through each item
for (Object o : a) {
JSONObject datos = (JSONObject) o;
System.out.println(datos);
}
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
UPDATED:
Once seen Enra64's answer, I don't know how to use getJSONArray and getJSONObject because it is not a method. I have included json-simple-1.1.1.jar to my project, but it doesn't work. Thank you in advance! This is my new code:
URL oracle = new URL("http://datos.santander.es/api/rest/datasets/callejero_calles.json?items=819"); // URL to Parse
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine = in.readLine();
JSONObject a = (JSONObject) parser.parse(inputLine);
JSONArray resources = a.getJSONArray("resources");
for (int i = 0; i < resources.length(); i++) {
resources.getJSONObject(i);
}

Select the resources object as follows:
JSONObject a = (JSONObject) parser.parse(inputLine);
JSONArray resources = a.getJSONArray("resources");
And then loop through it:
for (int i = 0; i < resources.length(); i++) {
resources.getJSONObject(i);
}

Related

java.lang.NoSuchMethodError: org.apache.fontbox.afm.AFMParser.parse()V

I'm having an error while using the apache PDFBox jar. It seems like somehow it is calling a method on the AFMParser class which is non-existent. AFAIK I have included fontbox properly. pdfbox,fontbox,commons and gson are all in my build path.
I guess the error must have something to do with referencing, but this is my first JAVA project and no real clue how to debug this further. If anyone has an idea, please advice.
Error log:
2018-03-16 14:26:50.020 java[1898:217675] java.lang.NoSuchMethodError: org.apache.fontbox.afm.AFMParser.parse()V
at org.apache.pdfbox.pdmodel.font.PDFont.addAdobeFontMetric(PDFont.java:166)
at org.apache.pdfbox.pdmodel.font.PDFont.addAdobeFontMetric(PDFont.java:152)
at org.apache.pdfbox.pdmodel.font.PDFont.getAdobeFontMetrics(PDFont.java:122)
at org.apache.pdfbox.pdmodel.font.PDFont.<clinit>(PDFont.java:114)
at org.apache.pdfbox.pdmodel.font.PDFontFactory.createFont(PDFontFactory.java:108)
at org.apache.pdfbox.pdmodel.PDResources.getFonts(PDResources.java:213)
at org.apache.pdfbox.util.PDFStreamEngine.getFonts(PDFStreamEngine.java:612)
at org.apache.pdfbox.util.operator.SetTextFont.process(SetTextFont.java:69)
at org.apache.pdfbox.util.PDFStreamEngine.processOperator(PDFStreamEngine.java:562)
at org.apache.pdfbox.util.PDFStreamEngine.processSubStream(PDFStreamEngine.java:269)
at org.apache.pdfbox.util.PDFStreamEngine.processSubStream(PDFStreamEngine.java:236)
at org.apache.pdfbox.util.PDFStreamEngine.processStream(PDFStreamEngine.java:216)
at org.apache.pdfbox.pdfviewer.PageDrawer.drawPage(PageDrawer.java:139)
at org.apache.pdfbox.pdmodel.PDPage.print(PDPage.java:890)
at java.desktop/sun.lwawt.macosx.CPrinterJob$6.run(CPrinterJob.java:757)
at java.desktop/sun.lwawt.macosx.CPrinterJob.printAndGetPageFormatArea(CPrinterJob.java:767)
at java.desktop/sun.lwawt.macosx.CPrinterJob.printLoop(Native Method)
at java.desktop/sun.lwawt.macosx.CPrinterJob.print(CPrinterJob.java:334)
at java.desktop/sun.print.RasterPrinterJob.print(RasterPrinterJob.java:1443)
at org.apache.pdfbox.pdmodel.PDDocument.print(PDDocument.java:1545)
at org.apache.pdfbox.pdmodel.PDDocument.silentPrint(PDDocument.java:1531)
at com.xlshopgroup.printingpc.WatchFolder.printPDFFromURL(WatchFolder.java:83)
at com.xlshopgroup.printingpc.WatchFolder.main(WatchFolder.java:118)
Exception: Error: End-of-File, expected line
My code:
import java.nio.file.*;
import java.io.*;
import java.net.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.awt.print.PrinterJob;
import java.awt.print.PageFormat;
import java.awt.print.Book;
import java.awt.print.*;
import java.awt.print.PrinterJob;
import javax.print.PrintService;
import javax.net.ssl.HttpsURLConnection;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.PrintPDF;
import org.apache.commons.*;
import org.apache.fontbox.*;
import com.google.gson.*;
public class WatchFolder {
public static JsonObject sendPost(
String APIURL
) throws Exception {
String APIBASEURL = "http://example.com";
URL obj = new URL(APIBASEURL+APIURL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JsonObject convertedObject = new Gson().fromJson(response.toString(), JsonObject.class);
return convertedObject;
}
public static void printPDFFromURL(
String pdfURL,
String printerName
) throws IOException,PrinterException {
PDDocument document = null;
try {
document = PDDocument.load(new URL(pdfURL));
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setJobName(pdfURL);
if(printerName != null ) {
PrintService[] printService = PrinterJob.lookupPrintServices();
boolean printerFound = false;
for(int i = 0;!printerFound && i < printService.length; i++) {
if(printService[i].getName().indexOf(printerName) != -1) {
printJob.setPrintService(printService[i]);
printerFound = true;
System.out.println("Printer found: " + printService[i].getName());
}
}
}
document.silentPrint( printJob );
}catch(Exception e) {
System.out.println("Exception: "+e.getMessage());
}finally {
if(document != null) {
document.close();
}
}
}
public static void main(
String[] args
) throws Exception {
JsonObject toBePrinted = sendPost("gettoprint");
JsonObject response = toBePrinted.getAsJsonObject("response");
JsonArray results = response.getAsJsonArray("results");
for (JsonElement result : results) {
JsonObject resultObj = result.getAsJsonObject();
String PackingSlipURL = resultObj.get("packing_slip_url").getAsString();
String StickerURL = resultObj.get("sticker_url").getAsString();
String ShippingPartner = resultObj.get("shipping_partner").getAsString();
String id = resultObj.get("id").getAsString();
printPDFFromURL(PackingSlipURL, "HP-idealbetalingen-printer");
printPDFFromURL(StickerURL, "Zebra?");
//JsonObject deletedFromQueue = sendPost("deletefromqueue/"+id);
}
}
}
#self; indeed as John Kane suggested, it had to do with version numbering. I was trying to use a 2.x.x version of fontbox with a 1.8.x version of pdfbox.

How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream)

I'm trying to read a json file from my local machine.
#Path("/")
public class JsonParsing {
File f = new File("file.json");
if (f.exists()){
InputStream is = new FileInputStream("file.json");
String jsonTxt = IOUtils.toString(is);
System.out.println(jsonTxt);
JSONObject json = new JSONObject(jsonTxt);
String a = json.getString("1000");
System.out.println(a);
}
}
But I'm getting error in toString() method.
Also is it possible to read a .txt file containing json object from my local machine? If possible, how it is done?
you may be using IOUtils and import sun.misc.IOUtils but the default does not include the method toString with parameter (InputStream) so you need to use apache common io lib to use this method and
import org.apache.commons.io.IOUtils;
Firstly: whenever you ask the question- add imports as well.
Secondly: yes it is possible to read a .txt file containing json object.
Steps:
1. Add Maven dependency in your pom.xml -
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
Or add the jar of this dependency.
2.imports in java file -
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
3. Sample Java code to read .txt file containing
this json object
{
"Name": "crunchify.com",
"Author": "App Shah",
"Company List": [
"Compnay: eBay",
"Compnay: Paypal",
"Compnay: Google"
]
}
#SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader(
"/Users/<username>/Documents/file1.txt"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("Name");
String author = (String) jsonObject.get("Author");
JSONArray companyList = (JSONArray) jsonObject.get("Company List");
System.out.println("Name: " + name);
System.out.println("Author: " + author);
System.out.println("\nCompany List:");
Iterator<String> iterator = companyList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (Exception e) {
e.printStackTrace();
}
}
Hope it helps.
Try:
File f = new File("file.json"); //it can be the same file "file.txt"
InputStream is = null;
if (f.exists()){
try {
is = new FileInputStream("file.json");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader r = new BufferedReader( new InputStreamReader( is ) );
StringBuilder stringBuilder = new StringBuilder();
String line;
String jsString = null;
try {
while (( line = r.readLine() ) != null) {
stringBuilder.append( line );
}
jsString = stringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println(jsString);
JSONObject jsonObj = new JSONObject(jsString);
String a = jsonObj.getString("1000");
System.out.println(a);
}
Refer to:
Creating JSONObject from text file

Example of POST request in Android studio

I just started learning android few days ago and I have a problem with uploading my JSON data to server. I manage to retrieve it via following code:
Edit: I did manage to retrieve files using external OKHTTP library but I would like to do this without using external libraries.
package cc.demorest;
import android.os.AsyncTask;
import android.renderscript.ScriptGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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 MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
task.execute("myserver.com");
}
//Downloadtask
public class DownloadTask extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection=null;
try {
url = new URL(urls[0]);
urlConnection=(HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data=reader.read();
while (data !=-1){
char current=(char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//After download task
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONArray jArray=new JSONArray(result);
JSONObject json_data = jArray.getJSONObject(1);
//Logging data
Log.i("Podatci: ", "Id: " + json_data.getInt("Id") +
", Name: " + json_data.getString("Name") +
", Years: " + json_data.getString("Age") +
", Email address: " + json_data.getString("Email")
);
TextView textView = (TextView) findViewById(R.id.textViewName);
textView.setText("ID: "+", Name: "+ json_data.getInt("Id")+json_data.getString("Name")+json_data.getString("Age")+json_data.getString("Email"));
/*
String data = jsonObject.getString("Name");
Log.i("Website content", data);
*/
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I am now trying to send my data to same server with same fields. I searched internet but most things that I found are outdated.. I would really appriciate some help or example.
Best Regards
Use HttpURLConnection, it does not use external libraries. If you're going to use an HttpURLConnection, it needs to be an AsyncTask.
Here is my code from a project I completed. Hope it helps.
First, put this in your manifest.xml file before :
<uses-permission android:name="android.permission.INTERNET" />
Calling the AsyncTask:
(Ignore the this, SinceTime, and GoesAddress. They are just variables I passed in)
URL url = new URL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
new ReceiveData(this, SinceTime, GoesAddress).execute(url);
The Class:
package com.ryan.scrapermain;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class ReceiveData extends AsyncTask<URL, Integer, Long> {
String response = "";
String SinceTime;
String GoesAddress;
Context myContext;
ReceiveData(Context context, String since, String goes) {
this.myContext = context;
SinceTime = since;
GoesAddress = goes;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder feedback = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
feedback.append("&");
feedback.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
feedback.append("=");
feedback.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return feedback.toString();
}
public void getData() throws IOException {
HashMap<String, String> params = new HashMap<>();
params.put("DCPID", GoesAddress);
params.put("SINCE", SinceTime);
URL url = new URL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
HttpURLConnection client = null;
try {
client = (HttpURLConnection) url.openConnection();
client.setRequestMethod("POST");
// You need to specify the context-type. In this case it is a
// form submission, so use "multipart/form-data"
client.setRequestProperty("multipart/form-data", "https://eddn.usgs.gov/fieldtest.html;charset=UTF-8");
client.setDoInput(true);
client.setDoOutput(true);
OutputStream os = client.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(params));
writer.flush();
writer.close();
os.close();
int responseCode = client.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
}
else {
response = "";
}
}
catch (MalformedURLException e){
e.printStackTrace();
}
finally {
if(client != null) // Make sure the connection is not null.
client.disconnect();
}
}
#Override
protected Long doInBackground(URL... params) {
try {
getData();
} catch (IOException e) {
e.printStackTrace();
}
// This counts how many bytes were downloaded
final byte[] result = response.getBytes();
Long numOfBytes = Long.valueOf(result.length);
return numOfBytes;
}
protected void onPostExecute(Long result) {
System.out.println("Downloaded " + result + " bytes");
// This is just printing it to the console for now.
System.out.println(response);
// In the following two line I pass the string elsewhere and decode it.
InputCode input = new InputCode();
input.passToDisplay(myContext, response);
}
}
Use Volley as defined here. It's far more easier.

java - update .json file (using json.simple)

I have a .json file that i am using like a property file. After reading the json file, i get the value from "Execute" node and then I want to update the "Execute" node with a value of "N".
My json file looks like this. {"RunDate":"2015-01-12","Execute":"Y"}. I wrote the code to read the json file and i am trying to update the file by writing a new file.
JSONParser parser = new JSONParser();
try {
FileReader fr = new FileReader("c:\\B\\myControl.json");
Object obj = parser.parse(fr);
JSONObject jsonObject = (JSONObject) obj;
ExecuteRun = (String) jsonObject.get("Execute");
RunDate = (String) jsonObject.get("RunDate");
//update
jsonObject.put("Execute", "N");
jsonObject.put("RunDate", RunDate);
FileWriter file = new FileWriter("c:\\B\\mycontrol.json", true);
try {
file.write(jsonObject.toJSONString());
} catch (Exception e) {
e.printStackTrace();
} finally {
file.flush();
file.close();
}
} catch(Exception e) {
e.printStackTrace();
}
The FileWriter line gets "access denied" error.
Can anyone help me out?
//this worked for me
package com.FLP.utils;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.FileWriter;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
#SuppressWarnings("unchecked")
public class TestDataReader {
public static void main(String[] args) {
try (Reader reader = new FileReader(".\\testdata\\TC_11.json")) {
// Read JSON file
JSONParser parser = new JSONParser();
JSONObject data = (JSONObject) parser.parse(reader);
data.put(key value);
#SuppressWarnings("resource")
FileWriter file = new FileWriter(".\\testdata\\TC_11.json");
file.write(data.toJSONString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
place this code
try (FileWriter file = new FileWriter("/C:/Users/itaas/Desktop/text1.txt")) {
file.write(js.toString());
System.out.println("Successfully Copied JSON Object to File...");
System.out.println("\nJSON Object: " + js);
}
} catch (Exception e) {
e.printStackTrace();
}

XML to Json using Json-lib

I'm trying to do a project in Android where I have a document xml from a web and i want to convert in Json.
I'm trying this:
URL url;
InputStream in;
try {
url = new URL("http://www.aemet.es/xml/municipios/localidad_41091.xml");
in = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String result, line = reader.readLine();
result = line;
while((line=reader.readLine())!=null){
result+=line;
}
XMLSerializer serializer = new XMLSerializer();
JSON json = serializer.read( result );
System.out.println(json.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
but does not work ... can someone help me
Send the entire xml document as string instead of reading line by line
import java.io.InputStream;
import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;
import org.apache.commons.io.IOUtils;
public class ConvertXMLtoJSON {
public static void main(String[] args) throws Exception {
InputStream is =
ConvertXMLtoJSON.class.getResourceAsStream("sample-xml.xml");
String xml = IOUtils.toString(is);
XMLSerializer xmlSerializer = new XMLSerializer();
JSON json = xmlSerializer.read( xml );
System.out.println( json.toString(2) );
}
}
If you want generic conversion you can use org.json

Categories

Resources