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");
Related
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
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);
See the following Code
socialMedia:
{
facebook: {
profileUrl: "https://www.facebook.com/pages/Mystic-Muffin/522896574410517?rf=157791610910510"
}
}
From the above we have to get the data
profileUrl: https://www.facebook.com/pages/Mystic-Muffin/522896574410517?rf=157791610910510
I am using the following code
JSONObject web=(JSONObject) jsonObject.get("socialMedia");
JSONObject web1=(JSONObject) jsonObject.get("facebook")
String fburl=(String) web.get("profileUrl");
i am getting the java.lang.NullPointerException
Help me to get this
JSONObject web=(JSONObject) jsonObject.get("socialMedia");
JSONObject web1=(JSONObject) web.get("facebook")
String fburl=(String) web1.get("profileUrl");
I am trying to deserialize the following incoming JSON data:
{"TimeTable":[{"PersonID":"100649771",
..,..,..,"xx":null},
{"PersonID":"100631701",
..,..,..,"xx":{"abc":1234,"xyz":5678}}],
"xxx":"","xxxx":0,"xxxxx":false}
But I am facing a problem while parsing using a custom deserialization block made up of:
jParser.nextToken();
while ((jParser.nextToken() != JsonToken.END_ARRAY)) {
String innerField = jParser.getCurrentName();
jParser.nextToken();
But in this way I am skipping the array contents While parsing for the second row in the array (as illustrated in the JSON sample above^).
UPDATE: Here is the method(PasteBin Link) which is trying to parse the JSON data coming in the described format. Is there a way I can bind the JSON data directly to my bean? (IMO it appeared way more complex to me as because of the JSON structure; Moreover I can't change the JSON structure nor the bean structure. So, I just dropped the idea of binding directly :| ) Anyways here(PasteBin Link) is the bean as well.
Following is the sample of the incoming JSON Data:
{"Schedules":[{"PersonID":"100649771",
"HasSchedule":false,
"TripType":null,
"StickerNumber":null,
"VehicleRegNo":null,
"ExpectedStartDate":null,
"ActualStartDate":null,
"ActualEndDate":null,
"PersonScheduledDate":null,
"Shift":null,
"ColdCall":null,
"PickupLocationCoord":null},
{"PersonID":"100631701",
"HasSchedule":true,
"TripType":"P",
"StickerNumber":"PC0409",
"VehicleRegNo":"ASJHAHSP1758",
"ExpectedStartDate":"16 Aug 2013, 10:00:00",
"ActualStartDate":"16 Aug 2013, 10:02:52",
"ActualEndDate":"16 Aug 2013, 14:14:12",
"PersonScheduledDate":null,
"Shift":"02:30 PM",
"ColdCall":"N",
"PickupLocationCoord":{"Latitude":92.01011101,"Longitude":48.01011101}}],
"ErrorMessage":"","ErrorCode":0,"HasError":false}
Please can anyone fireup some pointers for me here in order- to deserialize 'em correctly?
Thanks
UPDATED
Among other things, you are mixing up the two aproaches to read a JSON stream: using readTree() to get all your JSON data in a memory tree (like XML's DOM) but also using a JsonParser to read a JSON stream token by token (like XML's JAX). The following is a method that does almost the same using readTree(), which seems to be more appropriate to you as you are reading JSON already loaded in a String:
public List<VehicleInformationBean> getAllVehiclesInTree(String response) {
List<VehicleInformationBean> vehicleList = new ArrayList<VehicleInformationBean>();
try {
PersonInformationBean mPersonInformationBean;
DatabaseHelper mDatabaseHelper = DatabaseHelper.getInstance(sContext);
ObjectMapper mapper = new ObjectMapper();
ObjectNode root = (ObjectNode) mapper.readTree(response);
if ((root.get(ServiceConstant.ErrorCode).asInt()) != 0 || !root.has(ServiceConstant.Schedules)) {
return vehicleList;
}
for(JsonNode element: root.get(ServiceConstant.Schedules)) {
VehicleInformationBean lstVehicleInformation = new VehicleInformationBean();
if (element.has(ServiceConstant.PersonID)) {
String personId = element.get(ServiceConstant.PersonID).asText();
mPersonInformationBean = mDatabaseHelper.getPersonDetailById(personId);
lstVehicleInformation.setPersonID(personId);
lstVehicleInformation.setName(mPersonInformationBean.getName());
lstVehicleInformation.setPickupLocation(mPersonInformationBean.getPickupLocation());
lstVehicleInformation.setDropLocation(mPersonInformationBean.getDropLocation());
}
lstVehicleInformation.setTripType(element.get(ServiceConstant.TripType).textValue());
lstVehicleInformation.setStickerNumber(element.get(ServiceConstant.StickerNumber).textValue());
lstVehicleInformation.setVehicleRegNo(element.get(ServiceConstant.VehicleRegNo).textValue());
lstVehicleInformation.setExpectedStartDate(element.get(ServiceConstant.ExpectedStartDate).textValue());
lstVehicleInformation.setActualStartDate(element.get(ServiceConstant.ActualStartDate).textValue());
lstVehicleInformation.setActualEndDate(element.get(ServiceConstant.ActualEndDate).textValue());
lstVehicleInformation.setPersonScheduledDate(element.get(ServiceConstant.PersonScheduledDate).textValue());
lstVehicleInformation.setShift(element.get(ServiceConstant.Shift).textValue());
if (element.has("PickupLocationCoord")) {
JsonNode coords = element.get("PickupLocationCoord");
if(coords.has(ServiceConstant.Latitude)) {
lstVehicleInformation.setLatitude(coords.get(ServiceConstant.Latitude).asDouble());
}
if(coords.has(ServiceConstant.Longitude)) {
lstVehicleInformation.setLongitude(coords.get(ServiceConstant.Longitude).asDouble());
}
} else if (element.has(ServiceConstant.ColdCall)) {
lstVehicleInformation.setColdCall(element.get(ServiceConstant.ColdCall).textValue());
}
vehicleList.add(lstVehicleInformation);
}
} catch (Exception e) {
// TODO doing something with exception or throw it if it can't be handled here
e.printStackTrace();
}
return vehicleList;
}
There are some validations and extra code you need to add to this method for it to do exactly what your original method does. This method only shows you the main idea of how to do it.
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);