I am newbie in JAVA programming and trying to convert XML to JAVA using the below snipet.
Input File:
<?xml version="1.0" encoding="UTF-8"?>
-<ns0:MT_ECCJDBC xmlns:ns0="urn:xml:json">
-<REQUEST>
<ID>46565665</ID>
</REQUEST>
</ns0:MT_ECCJDBC>
The output :
{
"#xmlns:ns0": "urn:xml:json",
"REQUEST": ["46565665"]
}
The expected output in JSON is
{
"REQUEST":
{
" ID " : ["46565665"]
}
}
Below is my java code :
public class ConversionXMLtoJSON {
public static void main(String[] args) throws Exception {
{
InputStream is = ConversionXMLtoJSON.class.getResourceAsStream("instance.xml");
String xml = IOUtils.toString(is);
XMLSerializer xmlSerializer = new XMLSerializer();
JSON json = xmlSerializer.read( xml );
System.out.println( json.toString(2) );
}
}
}
Please suggest me to add in the code
To remove the tag "#xmlns:ns0": "urn:xml:json",
To add the ID element in the JAVA code.
Regards
You can map the XML into Java objects and then use JSON generator to generate the JSON. I like to use jackson-mapper-asl, jackson-core-asl and jackson-dataformat-xml.
To bind the XML to Java:
public class XmlRequest {
#JacksonXmlElementWrapper(localName="REQUEST")
private REQUEST request;
public static class REQUEST {
#JacksonXmlProperty(localName="ID")
protected int ID;
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
}
public REQUEST getRequest() {
return request;
}
public void setRequest(REQUEST request) {
this.request = request;
}
}
To Generate the JSON:
XmlMapper mapper = new XmlMapper();
XmlRequest request = (XmlRequest) mapper.readValue(App.class.getResourceAsStream("/NewFile.xml"), XmlRequest.class);
StringWriter sw = new StringWriter();
JsonGenerator jsongen = new JsonFactory().createJsonGenerator(System.out);
jsongen.writeStartObject();
jsongen.writeFieldName("REQUEST");
jsongen.writeStartObject();
jsongen.writeFieldName("ID");
jsongen.writeStartArray();
jsongen.writeNumber(request.getRequest().getID());
jsongen.writeEndArray();
jsongen.writeEndObject();
jsongen.writeEndObject();
jsongen.close();
Related
I have the following JSON file :
{
"btnsAssign": [
{
"btnCode": 1,
"btnItemTXT": "Baguette",
"btnItemCode": 1001,
"btnAvatarPath": "path"
},
{
"btnCode": 2,
"btnItemTXT": "Petit Pain",
"btnItemCode": 1002,
"btnAvatarPath": "path"
}
]
}
I have the below class :
BtnMenuAssignModel.java
public class BtnMenuAssignModel {
#SerializedName("btnsAssign")
#Expose
private List<BtnsAssign> btnsAssign = null;
public List<BtnsAssign> getBtnsAssign() {
return btnsAssign;
}
public void setBtnsAssign(List<BtnsAssign> btnsAssign) {
this.btnsAssign = btnsAssign;
}
}
BtnsAssign.java
public class BtnsAssign {
#SerializedName("btnCode")
#Expose
private Integer btnCode;
#SerializedName("btnItemTXT")
#Expose
private String btnItemTXT;
#SerializedName("btnItemCode")
#Expose
private Integer btnItemCode;
#SerializedName("btnAvatarPath")
#Expose
private String btnAvatarPath;
public Integer getBtnCode() {
return btnCode;
}
public void setBtnCode(Integer btnCode) {
this.btnCode = btnCode;
}
public String getBtnItemTXT() {
return btnItemTXT;
}
public void setBtnItemTXT(String btnItemTXT) {
this.btnItemTXT = btnItemTXT;
}
public Integer getBtnItemCode() {
return btnItemCode;
}
public void setBtnItemCode(Integer btnItemCode) {
this.btnItemCode = btnItemCode;
}
public String getBtnAvatarPath() {
return btnAvatarPath;
}
public void setBtnAvatarPath(String btnAvatarPath) {
this.btnAvatarPath = btnAvatarPath;
}
}
I need to update some object E.G: object btnItemTXT index 1 from "Petit Pain" to "Pain Complet", How can I?
First convert JSON file to BtnMenuAssignModel then modify BtnMenuAssignModel and convert BtnMenuAssignModel to JSON file:
Gson gson = new Gson();
// read initial json from jsonfile.json
FileReader reader = new FileReader(new File("D:\\codes\\gitlab\\jsonfile.json"));
BtnMenuAssignModel newModel = gson.fromJson(reader, BtnMenuAssignModel.class);
// modify the json object
newModel.getBtnsAssign().forEach(btnsAssign -> {
if (btnsAssign.getBtnCode() == 2) {
btnsAssign.setBtnItemTXT("Pain Complet");
}
});
// write new json string into jsonfile1.json file
File jsonFile = new File("D:\\codes\\gitlab\\jsonfile1.json");
OutputStream outputStream = new FileOutputStream(jsonFile);
outputStream.write(gson.toJson(newModel).getBytes());
outputStream.flush();
This is the right code working for me :
String file = "c:/Users/QAXX2121/Documents/a.json";
try {
Gson gson = new Gson();
// read initial json from jsonfile.json
FileReader reader = new FileReader(new File(file));
BtnMenuAssignModel newModel = gson.fromJson(reader, BtnMenuAssignModel.class);
// modify the json object
newModel.getBtnsAssign().forEach(btnsAssign -> {
if (btnsAssign.getBtnCode() == 2) {
btnsAssign.setBtnItemTXT("Taher");
}
});
// write new json string into jsonfile1.json file
File jsonFile = new File(file);
OutputStream outputStream = new FileOutputStream(jsonFile);
outputStream.write(gson.toJson(newModel).getBytes());
outputStream.flush();
I'm trying to unmarshal a XML with JAXB to convert it into an object, but the SOAPPArt, SOAPEnvelope and the SOAPBody are coming null I don't know why..
I've tried to unmarshal without the SOAPMessage as well but with no success.
Here is the XML i'm trying to unmarshal:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ObjectXmlResponse
xmlns="http://tempuri.org/testing">
<ResultadoXml xmlns="www.site.com.br">
<CodigoOperacao>dsadsdas</CodigoOperacao>
<OperacoesObjetoAnalise />
<Respostas>
<Resposta Final="true">
<Sistema>dsadfd</Sistema>
<Criterio>fdsfdsf</Criterio>
<Resposta>.</Resposta>
</Resposta>
</Respostas>
</ResultadoXml>
</ObjectXmlResponse>
</soap:Body>
</soap:Envelope>
Here are the classes:
#XmlRootElement(name="ObjectXmlResponse", namespace="http://tempuri.org/testing")
#XmlAccessorType(XmlAccessType.FIELD)
public class ObjectXmlResponse {
#XmlElement(name="ResultadoXml", namespace="www.site.com.br")
private ResultadoXml resultadoXml;
public ResultadoXml getResultadoXml() {
return resultadoXml;
}
public void setResultadoXml(ResultadoXml resultadoXml) {
this.resultadoXml = resultadoXml;
}
}
#XmlRootElement(name="ResultadoXml", namespace="www.site.com.br")
#XmlAccessorType(XmlAccessType.FIELD)
public class ResultadoXml {
private static final long serialVersionUID = 1L;
#XmlElement(name="CodigoOperacao")
private String codigoOperacao;
#XmlElement(name="OperacoesObjetoAnalise")
private String OperacoesObjetoAnalise;
#XmlElement(name="Respostas")
private Respostas respostas;
#XmlElement(name="Drivers")
private Drivers drivers;
public String getCodigoOperacao() {
return codigoOperacao;
}
public void setCodigoOperacao(String codigoOperacao) {
this.codigoOperacao = codigoOperacao;
}
public Respostas getRespostas() {
return respostas;
}
public void setRespostas(Respostas respostas) {
this.respostas = respostas;
}
public Drivers getDrivers() {
return drivers;
}
public void setDrivers(Drivers drivers) {
this.drivers = drivers;
}
public String getOperacoesObjetoAnalise() {
return OperacoesObjetoAnalise;
}
public void setOperacoesObjetoAnalise(String operacoesObjetoAnalise) {
OperacoesObjetoAnalise = operacoesObjetoAnalise;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String toString(){
return "ResultadoXml [codigoOperacao=" + codigoOperacao +"]";
}
}
And here is the unmarshal:
public static void main(String[] args) {
JAXBContext jaxbContext;
try {
String relatorio = <the xml>;
InputStream is = new ByteArrayInputStream(relatorio.getBytes());
SOAPMessage message = MessageFactory.newInstance().createMessage(null, is);
SOAPPart sp = message.getSOAPPart();
SOAPEnvelope env = sp.getEnvelope();
SOAPBody bdy = env.getBody();
jaxbContext = JAXBContext.newInstance(ObjectXmlResponse.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
ObjectXmlResponse response = (ObjectXmlResponse) jaxbUnmarshaller.unmarshal(new StringReader(relatorio));
System.out.println(response);
} catch(Exception ex) {
ex.printStackTrace();
}
System.exit(0);
}
I need to populate ObjectXmlResponse object and its attributes, like ResultadoXml.
Specify the namespace on all elements (or use #XmlSchema on the package) and unmarshall the SOAP body content using
ObjectXmlResponse response = (ObjectXmlResponse) jaxbUnmarshaller.unmarshal(bdy.extractContentAsDocument());
I have some code that takes in a list of descriptors and writes them to different JSON files using the GSON library. I am now trying to change that library to Jackson. I am not a Jackson expert so I'm looking for some help. Here is my code when I am using GSON:
Descriptor Class:
public class Descriptor {
#SerializedName("BatchName")
private String batchName;
#SerializedName("Metadata")
private Metadata metadata;
#SerializedName("SampleInfo")
private SampleInfoJsonModel sampleInfo;
#SerializedName("Files")
private List<String> files;
#SerializedName("ClientData")
private ClientData clientData;
#SerializedName("CaseName")
private String caseName;
public Descriptor() {
this.metadata = new Metadata();
this.sampleInfo = new SampleInfoJsonModel();
this.files = new ArrayList<String>();
this.clientData = new ClientData();
}
public String getBatchName() {
return batchName;
}
public void setBatchName(String batchName) {
this.batchName = batchName;
}
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
public SampleInfoJsonModel getSampleInfo() {
return sampleInfo;
}
public void setSampleInfo(SampleInfoJsonModel sampleInfo) {
this.sampleInfo = sampleInfo;
}
public List<String> getFiles() {
return files;
}
public void setFiles(List<String> files) {
this.files = files;
}
public ClientData getClientData() {
return clientData;
}
public void setClientData(ClientData clientData) {
this.clientData = clientData;
}
public String getCaseName() {
return caseName;
}
public void setCaseName(String caseName) {
this.caseName = caseName;
}
public ClientData getClientDataNoCountryCodes() {
// TODO Auto-generated method stub
return null ;
}
}
My write JSON File function:
public static void writeJsonFile(List<Descriptor> descriptors) {
try {
for(Descriptor descriptor : descriptors) {
BufferedWriter buffWrite = new BufferedWriter(new FileWriter("descriptor_"+descriptor.getCaseName()+".json"));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
buffWrite.write(gson.toJson(descriptor));
buffWrite.close();
}
}
catch (IOException ioe) {
System.err.println("Error while writing to json file in writeJsonFile: ");
ioe.printStackTrace();
}
}
Here is what I have written in Jackson:
BufferedWriter buffWrite = new BufferedWriter(new FileWriter("descriptor_"+descriptor.getCaseName()+".json"));
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
buffWrite.write(mapper.writeValueAsString(descriptor));
Is this the equivalent of the code below in GSON?
BufferedWriter buffWrite = new BufferedWriter(new FileWriter("descriptor_"+descriptor.getCaseName()+".json"));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
buffWrite.write(gson.toJson(descriptor));
buffWrite.close();
I think you are looking for generating a pretty JSON output for your Object and trying to write it into a file.
You have to make sure that you are using #SerializedName equivalent annotation from jackson which is #JsonProperty on your object properties.
Also you can use following to prettify JSON using jackson ObjectMapper
mapper.writerWithDefaultPrettyPrinter().writeValueAsString( descriptorObj )
NOTE that setting SerializationFeature.INDENT_OUTPUT will also help doing the same as you are already thinking.
Also Files APIs are really useful for file related operations.
I hope this will help!
I am working on an API that will return an JSON response from an XML source. I have used RestTemplate and JAXB to get the XML string from the source and then used StringReader and Unmarshaller to create the Java object. The object looks like this;
#XmlRootElement(name="ItemSearchResponse", namespace="http://webservices.amazon.com/AWSECommerceService/2011-08-01") //
#XmlAccessorType(XmlAccessType.FIELD)
public class SampleXML {
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType
public static class OperationRequest {
#XmlTransient
private String RequestId;
#XmlElement(name="RequestId")
public void setRequestId(String id) {
this.RequestId = id;
}
public String getRequestId() {
return RequestId;
}
...
This is the code that should return the JSON string to the browser;
#RequestMapping("/samplexml2")
public SampleXML CreateXMLFile2 () throws EncoderException, FileNotFoundException, SAXException {
try {
String requestUrl = null;
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new ResponseErrorHandler());
String decodedUrl = "http://localhost:8080/sample.xml";
String response = restTemplate.getForObject(decodedUrl, String.class);
//Prepare JAXB objects
JAXBContext jaxbContext = JAXBContext.newInstance(SampleXML.class);
Unmarshaller u = jaxbContext.createUnmarshaller();
//Create an XMLReader to use with our filter
XMLReader reader = XMLReaderFactory.createXMLReader();
//Create the filter (to add namespace) and set the xmlReader as its parent.
NamespaceFilter inFilter = new NamespaceFilter("http://webservices.amazon.com/AWSECommerceService/2011-08-01", true);
inFilter.setParent(reader);
//Prepare the input, in this case a java.io.File (output)
InputSource is = new InputSource(new StringReader(response));
//Create a SAXSource specifying the filter
SAXSource source = new SAXSource(inFilter, is);
//Do unmarshalling
SampleXML myJaxbObject = (SampleXML) u.unmarshal(source);
//Convert to myJaxbObject to JSON string here;
return myJaxbObject;
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
}
I want to write the conversation at this line; //Convert to myJaxbObject to JSON string here;
I have read many articles that point to this library; https://github.com/FasterXML/jackson-module-jaxb-annotations But I have not been able to use it successfully.
I would like an example that uses Jackson or MOXy dependencies
Have you tried simply changing your RequestMapping to #RequestMapping(value = "/samplexml2", produces = MediaType.APPLICATION_JSON_VALUE)?
I want to deserialize a JSON response but I'm not sure about the format. The format can vary in each case. For example the response contains a field named "error" which may be false (boolean) or an object that describes the error eg. "error": { "code": xxx , "description":"etc"}
How should I implement a class that covers both cases? Is there any way to do this?
Thanks
I would prefer using a TypeAdapter for your case:
private static class Error {
private boolean hasError;
private int code;
private String description;
}
private static class ErrorTypeAdapter extends TypeAdapter<Error> {
#Override
public Error read(JsonReader jsonReader) throws IOException {
Error response = null;
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String currentJsonName = jsonReader.nextName();
if("error".equals(currentJsonName)) {
response = new Error();
try {
response.hasError = jsonReader.nextBoolean();
} catch (Exception e) {
response.hasError = true;
jsonReader.beginObject();
}
} else if("code".equals(currentJsonName)) {
response.code = jsonReader.nextInt();
} else if ("description".equals(currentJsonName)) {
response.description = jsonReader.nextString();
}
}
if(response.hasError) {
jsonReader.endObject();
}
jsonReader.endObject();
return response;
}
#Override
public void write(JsonWriter jsonWriter, Error response)
throws IOException {
jsonWriter.beginObject();
jsonWriter.name("hasError").value(response.hasError);
jsonWriter.name("code").value(response.code);
jsonWriter.name("description").value(response.description);
jsonWriter.endObject();
}
}
To test it you can use:
String val1 = "{\"error\": {\"code\": 1 , \"description\":\"etc\"}}";
String val2 = "{\"error\": false}";
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Error.class, new ErrorTypeAdapter());
gsonBuilder.setPrettyPrinting();
final Gson gson = gsonBuilder.create();
gson.fromJson(val1, Error.class);
gson.fromJson(val2, Error.class);
You can read more about TypeAdapters here and also some great examples here.