How to convert JSON object to XML in UTF-8 format - java

I am trying to convert a JSON object to an XML document.
Below is the code,noting that I want to output the XML in UTF-8 format.
package com.test.json;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import org.json.JSONObject;
import org.json.XML;
public class ConvertJSONtoXML {
public static void main(String[] args) throws Exception {
BufferedReader jsonBuffer = new BufferedReader(new FileReader(new File("C:\\Users\\test\\Desktop\\sample-json.json")));
String line = null;
String json="";
while( (line=jsonBuffer.readLine())!=null){
json+=line; // here we have all json loaded
}
JSONObject jsonObject = new JSONObject(json);
System.out.println(XML.toString(jsonObject)); // here we have XML Code
jsonBuffer.close();
}
}
Can anyone please help on this. I have JSON data in Thai character.

Update your class to use an InputStreamReader instead of FileReader because InputStreamReaders can take the encoding charset as a second constructor argument:
public class ConvertJSONtoXML
{
public static void main(String[] args) throws Exception
{
File jsonFile = new File("C:\\Users\\test\\Desktop\\sample-json.json");
InputStreamReader reader = new InputStreamReader(new FileInputStream(jsonFile), "UTF-8");
BufferedReader jsonBuffer = new BufferedReader(reader);
String line;
StringBuilder json = new StringBuilder();
while ((line = jsonBuffer.readLine()) != null)
{
json.append(line); // here we have all json loaded
}
JSONObject jsonObject = new JSONObject(json.toString());
System.out.println(XML.toString(jsonObject)); // here we have XML Code
jsonBuffer.close();
}
}
The code has been also updated to use a StringBuilder for json tokens concatenation.

Related

How can I print the header of a .csv file in Java with package org.apache.commons.csv?

I use the following code to read a .csv file in Java. How can I print the header of the file using this code? (I use the packages edu.duke and org.apache.commons.csv from here.)
import edu.duke.*;
import org.apache.commons.csv.*;
import java.io.*;
public class myCSVParser {
public static void readData() {
FileResource fr = new FileResource("smauto2.csv");
CSVParser ps = fr.getCSVParser();
// ??
}
public static void main(String[] args) {
readData();
}
}
You can use this code
String fileName = "data.csv";
CSVReader reader = new CSVReader(new FileReader(fileName ));
// if the first line is the header
String[] header = reader.readNext();
OR
BufferedReader br = new BufferedReader(new FileReader("myfile.csv"));
String header = br.readLine();
if (header != null) {
String[] columns = header.split(",");
}

How to listen to JSON file update using java

I create java program that load JSON file from url , I push json object to this url every 20 seconds I want the program to give notification when the JSON file updated here is my java code
package com.company;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
public class Main {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONArray readJsonFromUrl(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 = readAll(rd);
JSONArray jsonArray = new JSONArray(jsonText);
return jsonArray;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONArray json = readJsonFromUrl("http://frozen-brook-16337.herokuapp.com/history.json");
for(int i=0;i<json.length();i++){
JSONObject jo=json.getJSONObject(i);
System.out.println(jo.get("data"));
}
}
}
How to make java program listen to JSON file update ?
You need to create a scheduler that executes your bit of code after every 20 seconds. There are multiple ways to achieve this.
A good robust way would be to use something like Quartz Scheduler
Or for a quick solution you can also create a Thread and have its run() method execute the code in a loop.
public class MyPush implements Runnable {
public void run() {
long twentySeconds = 20*1000L;
while(true) {
//execute your code
Thread.sleep(twentySeconds);
}
}
public static void main(String args[]) {
(new Thread(new MyPush())).start();
}
}

Displaying text retrieved from a Java class

I'm a beginner in Java. I have a 2 Java file that will passed the text retrieved from one Java file to the main Java file. But it doesnt seems to be working.
Main.java
import java.io.IOException;
public class LSAalgo extends Preprocessing {
public static void main(String[] args) throws IOException {
Preprocessing x = new Preprocessing(?);
}
}
Retrieve.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Preprocessing {
public void preprocessing(String text) throws IOException
{
BufferedReader in = new BufferedReader(new FileReader("input7.txt"));
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
}
}
Please help. Thanks.
You are just printing the text in console only. If you want to return complete text from one method to other just change your method return type to String (Since you are returning text) from void. Next change your code to
public String preprocessing() throws IOException
{
BufferedReader in = new BufferedReader(new FileReader("input7.txt"));
String line = "";
while((line = in.readLine()) != null)
{
System.out.println(line);
line += line;//appending complete text
}
in.close();
return line;//returning text
}
In main(-) change code to call preprocessing() method of Preprocessing class.
Preprocessing x = new Preprocessing();
String text = x.preprocessing();//getting text from Preprocessing class

Parsing Json witth Gson in Java

I'm trying to parse a local json file and the output is not what it's supposed to show.
I have little experience with Json (and Gson) so I'm unclear as to what the problem is.
Here is the tweet class:
public class tweet {
String from_user;
String from_user_name;
String profile_image_url;
String text;
public tweet(){
//empty constructor
}
}
This is the class where Gson is used:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import com.google.gson.Gson;
public class tweetfeedreader {
public static void main(String args[]) throws FileNotFoundException {
Gson gson = new Gson();
BufferedReader bufferedReader = new BufferedReader(new FileReader(
"C:/Users/LILITH/Desktop/jsonfile.json"));
tweet J_tweet = gson.fromJson(bufferedReader, tweet.class);
System.out.println(J_tweet);
}
}
Lastly, the .json file which i have saved onto a local directory:
http://search.twitter.com/search.json?q=%40android
there are no errors, but the output is:
tweet#3030d5aa
I'm uncertain as to what might be going wrong, so thanks for your guidance!
[Edit: I forgot to add that I have searched SO before and read the related posts. They may be similar but I am not having much luck in piecing the pieces together.]
Strip the results array out of that json, leaving nothing outside the []s.
Then this was just about the least I could modify the code to get it working:
import java.lang.reflect.*;
import java.io.*;
import java.util.*;
import com.google.gson.*;
import com.google.gson.reflect.*;
public class tweetfeedreader {
public static void main(String args[]) throws IOException {
Gson gson = new Gson();
BufferedReader bufferedReader = new BufferedReader(new FileReader(
"jsonfile.json"));
String line;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) sb.append(line);
Type tweetCollection = new TypeToken<Collection<tweet>>(){}.getType();
Collection<tweet> tweets = gson.fromJson(line, tweetCollection);
for (final tweet t : tweets) System.out.println(t.text);
}
}
System.out.println(J_tweet);
log in console reference on object J_tweet (tweet#3030d5aa)
Add method toString() to your tweet class
for example
#Override
public String toString()
{
return "from_user: " + from_user + "; from_user_name : " + from_user_name;
}

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