Conversion of JSON to XML - java

I am converting JSON Values to XML. Instead of getting JSON properties as elements of XML I am getting "title":"source". The output I wanted is <title>source</title>. What is the mistake I am doing? I am writing this code in JavaScript function.
I am using x2js plugin for conversion and I have included it using script tag.
My code to convert dynatree to JSON and JSON to XML is:
var x2js = new X2JS();
var tree = $("#source").dynatree("getTree").toDict();
alert(" tree:"+tree);
var jsonObject = JSON.stringify(tree);//dynatree to JSON
alert(" jsonObject :"+jsonObject);
var xmlAsStr = x2js.json2xml_str( jsonObject );//JSON to XML
alert("xml "+xmlAsStr);

Try to not use JSON.stringify(tree); this escapes the string.
Set var xmlAsStr = x2js.json2xml_str(tree);

Related

How to correctly generate Json without Backslashes

Problem:
I get json with backslashes as response from a GET Request
#RequestMapping(value = "repuve/recibe_captcha", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
like this:
{"mensaje":"Proceso ejecutado correctamente.","folio":"1652989601959","resultado":"{\"idSalida\":1,\"descSalida\":\"Proceso Correcto\",\"data\":[.....]}"}
When expected Result is like this:
{"mensaje":"Proceso ejecutado correctamente.","folio":"1652989601959","resultado":"{"idSalida":1,"descSalida":"Proceso Correcto","data":[.....]}"}
(The data array has a b64 image).
This is how json is created:
JSONObject object = new JSONObject();
JSONArray jArray = new JSONArray();
object.put("idSalida", 1);
object.put("descSalida", "Proceso Correcto");
jArray.put(captcha);
object.put("data", jArray);
I've tried some answers from StackOverflow using replace() but none of them seems to work for me.
Is there another way to remove the backslashes and get the correct json format delivered to front?
Thank you.
Any JSON generating framework should actually escape the nested quotation marks. If you expect the string to look differently, you will have write code that assembles that JSONary string the way you want.

playframework read json from post

I want to read a json sent to my controller via post.
When I do this:
System.out.println(request().body());
Result is:
DefaultRequestBody(None,None,None,None,None,Some(MultipartFormData(Map(json -> List({"a":"Test","b":"sssd"})),List(),List(),List())))
Now I will follow this documentation: https://www.playframework.com/documentation/2.5.x/JavaJsonActions
And I do this:
System.out.println(request().body().asJson());
Result is:
NULL
How can I access my json?
I also tried this:
Http.MultipartFormData multipartFormData = request().body().asMultipartFormData();
System.out.println(request().body());
System.out.println(request().body().asMultipartFormData());
System.out.println(multipartFormData.asFormUrlEncoded().get("a"));
It also returns null
Thanks to all
a possible solution is
Http.RequestBody body = request().body();
JsonNode json = body.asJson();
System.out.println(json);

MongoDB "NumberLong/$numberLong" issue while converting back to Java Object

I am having a json which is somethink like {"Header" : {"name" : "TestData", "contactNumber" : 8019071740}}
If i insert this to mongoDB it will be something like
{"_id" : ObjectId("58b7e55097989619e4ddb0bb"),"Header" : {"name" : "TestData","contactNumber" : NumberLong(8019071743)}
When i read this data back and try to convert to java object using Gson it throws exception com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a long but was BEGIN_OBJECT at line 1 column 109 path $.Header.contactNumber
I have found this, But i was wondering if i have very complex json structure then i might need to manipulate many json nodes in this approach.
Do anyone has any better alternatives on this.
Edit:1
I am reading querying and converting json as below
Document MongoDocument = mycollection.find(searchCondition);
String resultJson = MongoDocument.toJson();
Gson gson = new Gson();
Model model= gson.fromJson(resultJson, ItemList.class);
We can use below code:
Document doc = documentCursor.next();
JsonWriterSettings relaxed = JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build();
CustomeObject obj = gson.fromJson(doc.toJson(relaxed), CustomeObject.class);
Take a look at: converting Document objects in MongoDB 3 to POJOS
I had the same problem. The workaround with com.mongodb.util.JSON.serialize(document) does the trick.
Mongo db uses Bson format with its own types which follows json standards but it can't be parsed by json library without writing the custom wrapper/codec.
You can use third party framework/plugins to make the library take care of converting between document and pojo.
If that is not an option for you, you will have to do mapping yourself.
Document mongoDocument = mycollection.find(searchCondition);
Model model= new Model();
model.setProperty(mongoDocument.get("property");
Document.toJson() gives bson but not json.
I.e. for Long field myLong equals to xxx of Document it produces json like:
"myLong" : { "$numberLong" : "xxx"}
Parsing of such with Gson will not give myLong=xxx evidently.
To convert Document to Pojo using Gson you may do next:
Gson gson = new Gson();
MyPojo pojo = gson.fromJson(gson.toJson(document), MyPojo.class);
val mongoJsonWriterSettings: JsonWriterSettings = JsonWriterSettings.builder.int64Converter((value, writer) => writer.writeNumber(value.toString)).build
def bsonToJson(document: Document): String = document toJson mongoJsonWriterSettings

Read XML nodes after XML to JSON conversion in Java

I am trying to Convert my XML in to JSONObject and JSONArray, i want retrieve child nodes (example <ns2:make>) from JSONObject or JSONArray, can someone please help me how to read data from child nodes.
String TEST_XML_STRING ="<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">"+
"<S:Header/>"+
"<S:Body>"+
"<ns7:NewPORequest xmlns:ns2=\"http://services.m.com/ement/common\""+
"xmlns:ns5=\"http://services.m.com/ement/po\" xmlns:ns7=\"http://services.m.com/ementServices/ws\">"+
"<ns7:tracingLevel>OFF</ns7:tracingLevel>"+
"<ns7:userId>TestUtil</ns7:userId>"+
"<ns7:applicationId></ns7:applicationId>"+
"<ns7:userType>Buyer</ns7:userType>"+
"<ns5:PurchaseOrder>"+
"<ns5:poExternalId>XXX-930220</ns5:poExternalId>"+
"<ns5:repairOrderNumber>1234</ns5:repairOrderNumber>"+
"<ns5:estimateDetails>"+
"<ns2:estimatorFirstName></ns2:estimatorFirstName>"+
"<ns2:estimatorLastName></ns2:estimatorLastName>"+
"<ns2:estimateVersion>E1</ns2:estimateVersion>"+
"</ns5:estimateDetails>"+
"<ns5:quoteId>52452</ns5:quoteId>"+
"<ns5:supplierQuoteNumber>118596</ns5:supplierQuoteNumber>"+
"<ns5:documentName>Test_PO_1</ns5:documentName>"+
"<ns5:documentStatus>Submitted</ns5:documentStatus>"+
"<ns5:insuranceCompany>"+
"<ns2:VantiveCode>FA</ns2:VantiveCode>"+
"</ns5:insuranceCompany>"+
"<ns5:claimNumber></ns5:claimNumber>"+
"<ns5:shipToLocation>"+
"<ns2:address>"+
"<ns2:streetAddress></ns2:streetAddress>"+
"<ns2:streetAddress2>Suit 900</ns2:streetAddress2>"+
"<ns2:city></ns2:city>"+
"<ns2:stateCode>IL</ns2:stateCode>"+
"<ns2:zip>60654</ns2:zip>"+
"</ns2:address>"+
"<ns2:locationType>NotApplicable</ns2:locationType>"+
"</ns5:shipToLocation>"+
"<ns5:repairFacilityLocation>"+
"<ns2:repairFacilityID>4465</ns2:repairFacilityID>"+
"</ns5:repairFacilityLocation>"+
"<ns5:supplierLocation>"+
"<ns2:supplierId>5000</ns2:supplierId>"+
"</ns5:supplierLocation>"+
"<ns5:vehicleInfo>"+
"<ns2:vehicleOptionsMapCode>option map code"+
"</ns2:vehicleOptionsMapCode>"+
"<ns2:year>2006</ns2:year>"+
"<ns2:make>Nissan</ns2:make>"+
"<ns2:model>Titan</ns2:model>"+
"<ns2:modelNumber>model number</ns2:modelNumber>"+
"<ns2:vehicleEngineCode>engine code</ns2:vehicleEngineCode>"+
"<ns2:odometerReading>75013</ns2:odometerReading>"+
"<ns2:vehicleProductionDate></ns2:vehicleProductionDate>"+
"<ns2:bodyStyleCode>Body style code</ns2:bodyStyleCode>"+
"<ns2:bodyStyle>XYZ</ns2:bodyStyle>"+
"<ns2:cccVehicleId>XYZ001</ns2:cccVehicleId>"+
"</ns5:vehicleInfo>"+
"<ns5:requiredDeliveryDate>2013-05-04T15:26:35.219-06:00</ns5:requiredDeliveryDate>"+
"<ns5:comments>Delivery date important</ns5:comments>"+
"<ns5:createdDate>2013-05-04T15:26:35.219-06:00</ns5:createdDate>"+
"</ns5:PurchaseOrder>"+
"</ns7:NewPORequest>"+
"</S:Body>"+
"</S:Envelope>";
try {
JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
Object header=xmlJSONObj.get("S:Envelope");
JSONObject jsonObject = start.getJSONObject(0);
JSONArray dependencies = jsonObject.getJSONArray("list");
JSONArray dependencies = jsonObject.getJSONArray("getData");
String data = dependencies.getString(0);
System.out.println(data);
} catch (JSONException je) {
System.out.println(je.toString());
}
I have used JAXB is past but as this is for our Automation scripts and i want see if JSON can be used here, so that i don't have any dependencies on WSDL. "Object header=xmlJSONObj.get("S:Envelope");" does provide me header and other details but if i need vehicleInfo i will have to create object for all other parent tags.
I am able to resolve issue, it was issue with JSONObject, i was trying to access child node in below sequence.
test=xmlJSONObj.getJSONObject("S:Envelope").getJSONObject("S:Header").getJSONObject("").getJSONObject("ns7:NewPORequest").getString("ns7:tracingLevel");
Problem here is that when SOAP Messages gets converted into JSON, the header doesn't have any value, by removing header from my string i am able to get node values.
String test=xmlJSONObj.getJSONObject("S:Envelope").getJSONObject("S:Body").getJSONObject("ns7:NewPORequest").getString("ns7:userId");

JSON parsing. Unexpected character (t) at position 2. JAVA

I'm trying to parse JSON data from a google maps search.
I've tryed both JACKSON and and now I'm Trying JSON SIMPLE. Both of them gives the same error.
First of all I'm doing an search on Google maps.
String urlString = "http://maps.google.com/maps?f=q&source=s_q&output=json&start=0&q="+ "Stockholm" + "+Gym";
Gives me JSON while(1);{title:"stockholm Gym - Google Maps",url:"/maps?f=q\x26source=s_q\x26start=0\x26q=stockholm+Gym\x26ie=UTF8\x26hq=Gym.............. and so on.
I'm replacing the while(1); with ""; before i return the string.
To the problem when I'm trying to parse it
JSONParser parser = new JSONParser();
String jsonString = "";
// UriHandler.mapSearchJson is the method that returns the jsonString.
String jsonData = UriHandler.mapSearchJSON(jsonString);
Object obj = "";
try {
obj = parser.parse(jsonData);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject jsonObj = (JSONObject) obj;
String title = (String) jsonObj.get("title");
System.out.println(title);
This gives me the exception.
Unexpected character (t) at position 2.
When I'm debbuging it. comes all the way to when it's trying to parse the string. then the obj is = null.
What in thw world am I doing wrong.
Thanks!
As the others already mentioned, a nonquoted field name is not standard JSON. However, Jackson (and maybe others) has a set of option settings that allow it to work with nonstandard, but common JSON derivatives:
JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES
will enable processing of unquoted field names.
The response is not valid JSON, as the key name was not quoted with double quotes.
{title:"stockholm Gym"
is invalid JSON, it should be this:
{"title":"stockholm Gym"
Notice how title is surrounded by " double quotes
You are pulling back Javascript code that is meant for the maps.google.com site to use.
There could be any Javascript code in that response, not just the JSON that happens to be returned as part of the search.
You need to request from their maps API instead:
http://maps.googleapis.com/maps/api/geocode/json?address=Stockholm+Gym&sensor=false
This will return you only the JSON data.
Have a look the Google Maps API for more options.
I faced this error when trying to parse the json returned from kafka (kafka twitter producer).
The message returned was including some extra text other than json (KeyedMessage(twitter-test_english,null,null). Because of that I was facing this error.
KeyedMessage(twitter-test_english,null,null,{"created_at":"Sat Apr 23 18:31:10 +0000 2016","id":723942306777337856,"id_str":"723942306777337856"}
Pass only the message part from returned json and convert it into string.
{"created_at":"Sat Apr 23 18:31:10 +0000 2016","id":723942306777337856,"id_str":"723942306777337856"}
message = new KeyedMessage("twitter-test_english", (String)queue.take());
//System.out.println("This is message"+message.message());
String message_string = message.message().toString();
JsonParse.toParseJson(message_string);

Categories

Resources