XML to Json using Json-lib - java

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

Related

Read JSON in Java from URL that starts with unnecessary data

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

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

FileUtils.readFileToString() from Apache Commons IO works incorrectly with Cyrillic

I am using FileUtils.readFileToString to read contents of a text file with JSON at once. The file is UTF-8 encoded (w/o BOM). Yet, instead of cyrillic letters I get ?????? signs. Why?
public String getJSON() throws IOException
{
File customersFile = new File(this.STORAGE_FILE_PATH);
return FileUtils.readFileToString(customersFile, StandardCharsets.UTF_8);
}
FileUtils.readFileToString doesn't work with StandardCharsets.UTF_8.
Instead, try
FileUtils.readFileToString(customersFile, "UTF-8");
or
FileUtils.readFileToString(customersFile, StandardCharsets.UTF_8.name());
This is how I solved it back in 2015:
public String getJSON() throws IOException
{
// File customersFile = new File(this.STORAGE_FILE_PATH);
// return FileUtils.readFileToString(customersFile, StandardCharsets.UTF_8);
String JSON = "";
InputStream stream = new FileInputStream(this.STORAGE_FILE_PATH);
String nextString = "";
try {
if (stream != null) {
InputStreamReader streamReader = new InputStreamReader(stream, "UTF-8");
BufferedReader reader = new BufferedReader(streamReader);
while ((nextString = reader.readLine()) != null)
JSON = new StringBuilder().append(JSON).append(nextString).toString();
}
}
catch(Exception ex)
{
System.err.println(ex.getMessage());
}
return JSON;
}
I figured out that in logs all was fine, so I solved problem in rest controller:
#GetMapping(value = "/getXmlByIin", produces = "application/json;charset=UTF-8")

How to read .doc file line by line in java using all necessary jar file?

I want to display the difference between two .doc files line by line. I have done it with .txt files and it is working perfect. For this purpose I used the following code:
FileReader File1Reader = new FileReader(File1.getPath());
FileReader File2Reader = new FileReader(File2.getPath());
// Create Buffered Object.
BufferedReader File1BufRdr = new BufferedReader(File1Reader);
BufferedReader File2BufRdr = new BufferedReader(File2Reader);
// Get the file contents into String Variables.
String File1Content = File1BufRdr.readLine();
String File2Content = File2BufRdr.readLine();
//New String Builder
StringBuilder buffer = new StringBuilder();
Is there any way to read the doc files line by line.
I'm using following following code to read from doc file but this is not line by line. Here is the code:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class read_From_Doc_Docx {
public static void main(String[] args) {
//Alternate between the two to check what works.
//String FilePath = "D:\\Users\\username\\Desktop\\Doc1.docx";
String FilePath = "/Users/esna786/Removal of Redundancy.docx";
FileInputStream fis;
if (FilePath.substring(FilePath.length() - 1).equals("x")) { //is a docx
try {
fis = new FileInputStream(new File(FilePath).getAbsolutePath());
XWPFDocument doc = new XWPFDocument(fis);
XWPFWordExtractor extract = new XWPFWordExtractor(doc);
System.out.println(extract.getText());
} catch (IOException e) {
e.printStackTrace();
}
} else { //is not a docx
try {
fis = new FileInputStream(new File(FilePath));
HWPFDocument doc = new HWPFDocument(fis);
WordExtractor extractor = new WordExtractor(doc);
System.out.println(extractor.getText());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Just use getParagraphText() method instead of getText().

gson with mixed read

I'm trying to read json with gson, but I can't get a "simple" gson example to work.
From: https://sites.google.com/site/gson/streaming
public List<Message> readJsonStream(InputStream in) throws IOException {
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
List<Message> messages = new ArrayList<Message>();
reader.beginArray();
while (reader.hasNext()) {
Message message = gson.fromJson(reader, Message.class);
messages.add(message);
}
reader.endArray();
reader.close();
return messages;
}
Here's the problem, if I try with:
JsonReader reader;
Gson gson = new Gson();
gson.fromJson(reader,Program.class);
It doesn't even build.
The method fromJson(String, Class<T>) in the type Gson is not applicable for the arguments (JsonReader, Class<Program>)
There seems to be a method according to eclipse:
fromJson(JsonReader arg0, Type arg1)
Replace
import android.util.JsonReader;
with
import com.google.gson.stream.JsonReader
did it! =)
It is mentionned that the fromJson method accepts argument 0 as a String. Try to create a method that transforms the inputStream to a String.
static public String generateString(InputStream stream) {
InputStreamReader reader = new InputStreamReader(stream);
BufferedReader buffer = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
try {
String cur;
while ((cur = buffer.readLine()) != null) {
sb.append(cur).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}

Categories

Resources