Axis2 JSon Support (Jettison) bad xml conversion - json

I am using Axis2 1.6.4 to implement REST Json WebServices (https://axis.apache.org/axis2/java/core/docs/json_support.html) and I face an issue when Jettison converts Json object To XML if it does not have a "root" element. Details:
If request is:
{"name":"John","age":30}
Then XML OMElement at server side is:
<name>John</name
So age element is missed
Instead, if request is:
{person:{"name":"John","age":30}}
Then XML OMElement at server side is:
<person><name>John</name><age>30</age></person>
Thanks for your help,
Martí

I've founda work around to overcome this JSON->XML conversion issue. Thanks to this post:How to use Axis2 JSON, I've realized I am able to access input json before converting it to XML, and also to create an OMElement from a json string. So when input is a json request, I wrap it with a json "root" element, and then convert it to XML without losing data.
If it could be useful to someone, below is the source code to get input json string and the source code to convert json string to OMElement
Get input json string and wrap into a root
OMSourcedElement source=(OMSourcedElement )msg;
AbstractJSONDataSource jsonSoucre=(AbstractJSONDataSource)source.getDataSource();
MessageContext msgCtxt= MessageContext.getCurrentMessageContext();
JSONDataSource jsonRequestEnvDS= new JSONDataSource(new StringReader("{\"JSONEnvelope\": " + jsonSoucre.getObject() + " }"), msgCtxt);
OMFactory factory = OMAbstractFactory.getOMFactory();
OMSourcedElement omRequest = factory.createOMElement(jsonRequestEnvDS,null,null);
Create an OMElement from a json string
String jsonString="{...}";
JSONDataSource jsonDS= new JSONDataSource(new StringReader(jsonString),msgCtxt);
factory = OMAbstractFactory.getOMFactory();
OMSourcedElement resonseJson = factory.createOMElement(jsonDS,null,null);
return resonseJson;

Related

Ruby parse string to json

So I have some json that looks like this, which I got after taking it out of some other json by doing response.body.to_json:
{\n \"access_token\": \"<some_access_token>\",\n \"token_type\": \"Bearer\",\n \"expires_in\": 3600,\n \"id_token\": \<some_token>\"\n}\n"
I want to pull out the access_token, so I do
to_return = {token: responseJson[:access_token]}
but this gives me a
TypeError: no implicit conversion of Symbol into Integer
Why? How do I get my access token out? Why are there random backslashes everywhere?
to_json doesn't parse JSON - it does the complete opposite: it turns a ruby object into a string containing the JSON representation of that object is.
It's not clear from your question what response.body is. It could be a string, or depending on your http library it might have already been parsed for you.
If the latter then
response.body["access_token"]
Will be your token, if the former then try
JSON.parse(response.body)["access_token"]
Use with double quotes when calling access_token. Like below:
to_return = {token: responseJson["access_token"]}
Or backslashes are escaped delimiters and make sure you first parse JSON.

Jettison can not convert json string to json object when there is an element has empty string value

My application is using camel rest (2.15.2) to catch a POST json String and then uses jettison to convert to a JSON Object. It is working fine with normal request.
POST request: {"request"={"lname"="aaa", "fname"="bb"}}
1. String body = exchange.getIn().getBody(String.class);
2. JSONObject obj = new JSONObject(body);
When i debug, variable body = {request={lname=aaa, fname=bb}}.
And line 2 returns a JSONObject. so far so good
if we try to another the request:
{"request"={"lname"=" ", "fname"="aa"}}
then body = {request={lname= , fname=aa}}
line2 returns Exception.
Could you please help me to fix this issue: convert json string which contains element has empty value string to json object.
The above request is acceptable in my scenarios.
Error:
org.codehaus.jettison.json.JSONException: Missing value. at character
15 of {request={lname= , fname=aa}} at
org.codehaus.jettison.json.JSONTokener.syntaxError(JSONTokener.java:463)
at
org.codehaus.jettison.json.JSONTokener.nextValue(JSONTokener.java:356)
at org.codehaus.jettison.json.JSONObject.(JSONObject.java:230)
at
org.codehaus.jettison.json.JSONTokener.newJSONObject(JSONTokener.java:412)
at
org.codehaus.jettison.json.JSONTokener.nextValue(JSONTokener.java:327)
at org.codehaus.jettison.json.JSONObject.(JSONObject.java:230)
at org.codehaus.jettison.json.JSONObject.(JSONObject.java:311)

JsonConvert.DeserializeObject

I am trying to DeserializeObject but have not idea how to reach the object within the brackets []
dynamic response = null;
response = JsonConvert.DeserializeObject(apiResponseContent);
apiResponseContent =
"CasinoId: " + response.Result.FirstName + "\r\n" +
"PlayerId: " + response.Result.Id
The response which I am trying to parse it:
"{\"Status\":{\"ErrorCode\":0,\"ErrorName\":\"SUCCEED\",\"ErrorMessage\":\"\",\"ReferenceNumber\":\"\"},\"Result\":[{\"FirstName\":Adam,\"Id\":6161999\"}]}"
Would appreciate as answer
I believe you can access fields in the JSON object using a key collection, so response["keynamehere"].
But the best way is to create an object that mimics the objects and fields of your JSON object, and then you can deserialize to that object and it will map the fields. (ie: JsonConvert.DeserializeObject<YOUROBJECTHERE>(apiResponseContent))
Please see some reference links on how to do that in more detail:
http://www.newtonsoft.com/json/help/html/DeserializeObject.htm
Deserializing JSON data to C# using JSON.NET
If you want to get a bit more fancy, you can create your own custom converter:
Deserialize the JSON where the values are field names with JSON.NET

How can I define a ReST endpoint that allows json input and maps it to a JsonSlurper

I want to write an API ReST endpoint, using Spring 4.0 and Groovy, such that the #RequestBody parameter can be any generic JSON input, and it will be mapped to a Groovy JsonSlurper so that I can simply access the data via the slurper.
The benefit here being that I can send various JSON documents to my endpoint without having to define a DTO object for every format that I might send.
Currently my method looks like this (and works):
#RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> putTest(#RequestBody ExampleDTO dto) {
def json = new groovy.json.JsonBuilder()
json(
id: dto.id,
name: dto.name
);
return new ResponseEntity(json.content, HttpStatus.OK);
}
But what I want, is to get rid of the "ExampleDTO" object, and just have any JSON that is passed in get mapped straight into a JsonSlurper, or something that I can input into a JsonSlurper, so that I can access the fields of the input object like so:
def json = new JsonSlurper().parseText(input);
String exampleName = json.name;
I initially thought I could just accept a String instead of ExampleDTO, and then slurp the String, but then I have been running into a plethora of issues in my AngularJS client, trying to send my JSON objects as strings to the API endpoint. I'm met with an annoying need to escape all of the double quotes and surround the entire JSON string with double quotes. Then I run into issues if any of my data has quotes or various special characters in it. It just doesn't seem like a clean or reliable solution.
I open to anything that will cleanly translate my AngularJS JSON objects into valid Strings, or anything I can do in the ReST method that will allow JSON input without mapping it to a specific object.
Thanks in advance!
Tonya

Json Parsing in Mirth OR Json in Mirth OR HL7 to JSON in Mirth

I want to use JSON as input of mirth channel and output like details Save in db or Create HL7 message.
In short Input as JSON Parse it and output as any format.
var object = {};
//Create JSON Object from HL7 Message.
object.mrn = msg['PID']['PID.3']['PID.3.1'].toString();
object.firstName = msg['PID']['PID.5']['PID.5.2'].toString();
object.lastName = msg['PID']['PID.5']['PID.5.1'].toString();
object.dob = msg['PID']['PID.7']['PID.7.1'].toString();
object.ssn = msg['PID']['PID.19']['PID.19.1'].toString();
//Create string from JSON Object.
var objjson = JSON.stringify(object);
logger.info(objjson);
//Create Json Object From JSON string.
var tt = JSON.parse(objjson);
Output
{"mrn":"1001","firstName":"COLLEEN","lastName":"OHALLAHAN","dob":"19850704","ssn":"123456789"}
HL7Message Sample
MSH|^~\&|ADT1|SHM|SHMADT|SHM|200812091126|SECURITY|ADT^A01^ADT_A01|MSG00001|P|2.5|
EVN|A01|200812091126||
PID|1|1001|1001^5^M11^ADT1^MR^SHM||OHALLAHAN^COLLEEN^^||19850704|F||2106-3|1200 N ELM STREET^^NEWPORT BEACH^CA^92660-1020^US^H|OC|(949) 555-1234|(949) 555-5678||S||PATID1001^2^M10^ADT1^AN^A|123456789|U1234567^CA|
NK1|1|OHALLAHAN^BRITTANY^M|SIS^SISTER||||N^NEXT-OF-KIN
PV1|1|I|2000^2012^01||||001122^ZOIDBERG^JOHN^|||SUR||||1|A0|
I was parsing through this page, and found your code Rikin patel. Actually when You create object and display it, it may appear in the console as a JSON data, when when you look your output it will be the normal XML driven format. But instead of the object when you use msg as below:
msg = JSON.stringify(object); //converting msg into JSON object
logger.info("json data:" + msg); //displaying the JSOn message
You will find the data being modified in the output.
As Per #Debugger, If some one want json file as input/Source then try this solution.
Mirth channel
Inbound Datatype as delimited text
Outbound DataType as Javascript
Make JavaScript Type of Destination and Write below code in Transformer:
//Create Json Object From JSON string.
var objJson = JSON.parse(messageObject.getRawData());
logger.info(objJson.propertyName);
Input:
{"mrn":"1001","firstName":"COLLEEN","lastName":"OHALLAHAN","dob":"19850704","ssn":"123456789"}
Output:
logger.info(objJson.firstName);
COLLEEN
Note:
Use connectorMessage.getRawData() instead of messageObject.getRawData() for Mirth 3.0+ version.
To receive JSON as Input in mirth channel, set inbound datatype as delimited text and in channel pre processor create Json object from received message and return the json object.
use the json object to get the details and store in some variables and use DB writer to save in db.
To build hl7 message, mirth provides few functions such as createSegment(seg name, index) to easily build your own hl7 message.