json to xml java - java

I want convert json to xml
here is code
public class ConvertJSONtoXML {
public static void main(String[] args) throws Exception {
InputStream is = ConvertJSONtoXML.class.getResourceAsStream("demo1.txt");
String jsonData = IOUtils.toString(is);
XMLSerializer serializer = new XMLSerializer();
JSON json = JSONSerializer.toJSON(jsonData);
String xml = serializer.write((JSON) json);
System.out.println(xml);
Here is demo1.txt
{"name":"naveed" }
It reads demo1.txt file and convert into xml but i m trying to pass json as string.
String jsonString="{\"name\":\"naveed\" }";
InputStream is = ConvertJSONtoXML.class.getResourceAsStream(jsonString);
but it wont work for string..
i thing getResourceAsStream(jsonString) doesnt work for string....
please suggest any reference

The method getResourceAsStream() actually looks on the file system for resource identified by the input string and open an input stream for it.
You should rather use something like
InputStream is = new ByteArrayInputStream( jsonString.getBytes() );
Also, you should take care of using compatible charsets.

Related

Convert JSON String to File in Java

I'm trying to convert an Object to JSON then convert it to File
to be able to send it to AWS S3.
Is there a way to convert the String in the most efficient way?
Thank you!
Here is my code:
String messageBody = new Gson().toJson(thisIsADtoObject);
And for the S3
PutObjectRequest request = new PutObjectRequest(s3BucketName, key, file);
amazonS3.putObject(request);
As far as I know, to create a file object to send to AWS, you will have to create the actual file on disk, e.g. with a PrintStream:
File file = new File("path/to/your/file.name");
try (PrintStream out = new PrintStream(new FileOutputStream(file))) {
out.print(messageBody);
}
Instead of using the constructor taking a file, you might want to use the one which takes an InputStream:
PutObjectRequest request = new PutObjectRequest(s3BucketName, key, inputStream, metadata);
amazonS3.putObject(request);
To convert a String to an InputStream, use
new ByteArrayInputStream(messageBody.getBytes(StandardCharsets.UTF_8));
Link to SDK JavaDoc
public class JSONStringToFile {
public static void main(String[] args) throws IOException {
JSONObject obj = new JSONObject();
obj.put("Name", "somanna");
obj.put("city", "bangalore");
JSONArray company = new JSONArray();
company.add("Compnay: mps");
company.add("Compnay: paypal");
company.add("Compnay: google");
obj.put("Company List", company);
// try-with-resources statement based on post comment below :)
try (FileWriter file = new FileWriter("/Users/<username>/Documents/file1.txt")) {
file.write(obj.toJSONString());
System.out.println("Successfully Copied JSON Object to File...");
System.out.println("\nJSON Object: " + obj);
}
}
}
It's much easier with version 2 of the AWS Java SDK.
If you have converted the object to a JSON String, using GSON or Jackson, you can upload it via:
PutObjectRequest putObjectRequest = PutObjectRequest.builder().bucket(bucket).key(s3Key).build();
s3Client.putObject(putObjectRequest, RequestBody.fromString(jsonString));
No need to set the content length manually.

converting xml to java objects with xstream in java

I have an xml ans i want to make it objects , i am using xsteam for this and I have added xstream jars in my classpath..
below is my xml...
<Eurexflows xmlns:eur="http://www.eurexchange.com/EurexIRSFullInventoryReport" xmlns:fpml="http://www.fpml.org/FpML-5/confirmation">
<EurexMessageObject>
<CCPTradeId>109599</CCPTradeId>
<novDateTime>2012-02-15 10:59:00.0</novDateTime>
</EurexMessageObject>
<EurexMessageObject>
<CCPTradeId>122270</CCPTradeId>
<novDateTime>2012-06-29 18:59:00.0</novDateTime>
</EurexMessageObject>
</Eurexflows>
below is my pojo...
public class EurexMessageObject {
private Long CCPTradeId;
private String migratedDate;
public Long getCCPTradeId() {
return CCPTradeId;
}
public void setCCPTradeId(Long cCPTradeId) {
CCPTradeId = cCPTradeId;
}
public String getMigratedDate() {
return migratedDate;
}
public void setMigratedDate(String migratedDate) {
this.migratedDate = migratedDate;
}
}
and in my main class I have coded this way..
String xmlInputtra="C:\\Rahul\\InputXml\\Xmloutput.xml";
try
{
// get XStream instance and set required aliases
XStream xstream = new XStream();
xstream.alias("EurexMessageObject", com.rbos.gdspc.eurex.EurexMessageObject.class);
// prepare cash flow message from xslt output
EurexMessageObject eurexflowMsg = (EurexMessageObject) xstream.fromXML(xmlInputtra);
System.out.println(eurexflowMsg.toString());
}catch(Exception e)
{
e.printStackTrace();
}
now upon debuging I am getting the following exception..please advise how can I overcome from this
com.thoughtworks.xstream.io.StreamException: : only whitespace content allowed before start tag and not C (position: START_DOCUMENT seen C... #1:1)
Well,the thing that is overlooked here is how you are reading in the XML file.you are using the method fromXML which is expecting the actual XML input and not the file name. So when it parses your xml (which is "Xmloutput.xml" not the actual xml)
I suggest you to use a FileReader/BufferedReader in order to get the contents of the XML back. Something like this should work:
XStream instream = new XStream();
BufferedReader br = new BufferedReader(new FileReader("Xmloutput.xml"));
StringBuffer buff = new StringBuffer();
String line;
while((line = br.readLine()) != null){
buff.append(line);
}
EurexMessageObject eurexflowMsg = (EurexMessageObject)instream.fromXML(buff.toString());
I hope it will help you, best regards.
Here path for XML file:
String xmlInputtra="C:\\Rahul\\InputXml\\Xmloutput.xml";
is treated as XML contents,
so you need to pass as String for that you can read file and pass to constructor.

Need to convert from XML to HTML in java

Please give me suggestion as i need to convert from XML to HTML in java without using XSLT. As i was searching in the web but everywhere it was showing can convert from xml to html with use of only xslt/xsl?
Please guyz give me some suggestions?
You can parse xml data using jQuery.parseXML and use data of it.
$.get('/url_of_the_xml_resource')
.done(function(data){
// parse the xml
data = $.parseXML(data);
//
// do anything you want with the parsed data
})
.fail(function(){
alert('something went wrong!');
})
;
This will save root.xml's content as root.xml.html.
public static void main(String[] args) throws Exception {
String xmlFile = "root.xml";
Scanner scanner = new Scanner(new File(xmlFile)).useDelimiter("\\Z");
String xmlContent = scanner.next();
xmlContent = xmlContent.trim().replaceAll("<","<").replaceAll(">",">").replaceAll("\n", "<br />").replaceAll(" ", " ");
PrintWriter out = new PrintWriter(xmlFile+".html");
out.println("<html><body>" + xmlContent + "</body></html>");
scanner.close();
out.close();
}
Note: This will retain the XML's original indentation and line breaking.
You can use StringEscapeUtils
and use the method escapeHtml.
String yourXmlAsHtmlString = StringEscapeUtils.escapeHtml(yourXmlAsString);

How to convert String to Json

I have a servlet in Java and I would like to know how I can do the following.
I have a String variable with the value of a name and want to create a Json with the variable being something like {"name": "David"}.
How do I do this?
I have the following code but I get an error :
Serious: Servlet.service () for servlet threw
exception servlet.UsuarioServlet java.lang.NullPointerException
at servlet.UsuarioServlet.doPost (UsuarioServlet.java: 166):
at line
String myString = new JSONObject().put("name", "Hello, World!").toString();
Your exact problem is described by Chandra.
And you may use the JSONObject using his suggestion.
As you now see, its designers hadn't in mind the properties, like chaining, which made the success of other languages or libs.
I'd suggest you use the very good Google Gson one. It makes both decoding and encoding very easy :
The idea is that you may define your class for example as :
public class MyClass {
public String name = "Hello, World!";
}
private Gson gson = new GsonBuilder().create();
PrintWriter writer = httpServletResponse.getWriter();
writer.write( gson.toJson(yourObject));
The json library based on Map. So, put basically returns the previous value associated with this key, which is null, so null pointer exception.( http://docs.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html#put%28java.lang.Object,%20java.lang.Object%29)
You can rewrite the code as follows to resolve the issue.
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("name", "Hello, World");
String myString = jsonObject1.toString();
I tried with GSON, GSON is directly convert your JSONString to java class object.
Example:
String jsonString = {"phoneNumber": "8888888888"}
create a new class:
class Phone {
#SerializedName("phoneNumber")
private String phoneNumebr;
public void setPhoneNumber(String phoneNumebr) {
this.phoneNumebr = phoneNumebr;
}
public String getPhoneNumebr(){
return phoneNumber;
}
}
// in java
Gson gson = new Gson();
Phone phone = gson.fromJson(jsonString, Phone.class);
System.out.println(" Phone number is "+phone.getPhoneNumebr());

Problems converting from an object to XML in java

What I'm trying to do is to convert an object to xml, then use a String to transfer it via Web Service so another platform (.Net in this case) can read the xml and then deparse it into the same object. I've been reading this article:
http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#start
And I've been able to do everything with no problems until here:
Serializer serializer = new Persister();
PacienteObj pac = new PacienteObj();
pac.idPaciente = "1";
pac.nomPaciente = "Sonia";
File result = new File("example.xml");
serializer.write(pac, result);
I know this will sound silly, but I can't find where Java creates the new File("example.xml"); so I can check the information.
And I wanna know if is there any way to convert that xml into a String instead of a File, because that's what I need exactly. I can't find that information at the article.
Thanks in advance.
And I wanna know if is there any way to convert that xml into a String instead of a File, because that's what I need exactly. I can't find that information at the article.
Check out the JavaDoc. There is a method that writes to a Writer, so you can hook it up to a StringWriter (which writes into a String):
StringWriter result = new StringWriter(expectedLength);
serializer.write(pac, result)
String s = result.toString();
You can use an instance of StringWriter:
Serializer serializer = new Persister();
PacienteObj pac = new PacienteObj();
pac.idPaciente = "1";
pac.nomPaciente = "Sonia";
StringWriter result = new StringWriter();
serializer.write(pac, result);
String xml = result.toString(); // xml now contains the serialized data
Log or print the below statement will tell you where the file is on the file system.
result.getAbsolutePath()

Categories

Resources