How to convert ManagedCursorStreamProvider to JSOn object in mule 4 - json

How to convert ManagedCursorStreamProvider to Json object in mule.
I have written a java method which takes the Json Object as input
Request Payload:
{ a: "one",
b : "two"}
Invoke static
arg0 : payload
Java Function called using invoke static
public static func(JsonObject json){
}
I am getting the following error:
Expected arguments are [com.google.gson.JsonObject jsonObject] and
invocation was attempted with arguments
[org.mule.runtime.core.internal.streaming.bytes.ManagedCursorStreamProvider
arg0].
No suitable transformation was found to match the expected type for
the parameter [jsonObject].
UPDATE:
I have updated my java method to accept String as input.
"Cannot coerce Object { encoding: UTF-8, mediaType: application/json; charset=UTF-8, mimeType: application/json, raw: org.mule.weave.v2.el.SeekableCursorStream#868075a } (org.mule.weave.v2.el.MuleTypedValue#7c0c5e89) to String
1| arg0 : vars.req as String
^^^^^^^^^^^^^^^^^^
Trace:
at main (line: 1, column: 8)" evaluating expression: "arg0 : vars.req as String".

Mule doesn't know how to convert to a GSON JsonObject. You can use DataWeave to transform it into a Java map. Alternatively, you can change the argument of the Java method to String and Mule will transparently convert the stream to a String. Be sure to use the latest version of the Java module.
If you want to convert to a custom type of object you will need to implement it yourself in Java.

Related

How do I correctly deserialize json that consists of a list item that includes another object?

The client I am using returns json like this:
[
{
"source": "ANY"
}
]
That is, the element of the array that the object is in.
I'm trying to make a request like this:
restTemplate.postForObject<AbcdResponse>(
"/address",
listOf(value).let { JsonHttpEntity(it) }
)
data class AbcdResponse(
val obj: AbcdObject
)
data class DaDataAddress(
val source: String?
)
But I get the HttpMessageNotReadableException exception:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `com.app.client.abcd.domain.AbcdResponse` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.app.client.abcd.domain.AbcdResponse` out of START_ARRAY token
at [Source: (ByteArrayInputStream); line: 1, column: 1]
How can I deserialize the response correctly?
As you probably noticed, the response as a whole is a JSON array. You can tell by the square brackets [ ... ] surrounding the whole thing.
Because of this, you cannot deserialize it as an object (such as AbcdResponse). What you should do instead is use List<DaDataAddress> instead of AbcdResponse.
You don't really need AbcdResponse. What you need is to use a ParameterizedTypeReference as follows while calling the service:
restTemplate.exchange("/address",
HttpMethod.POST,
listOf(value).let { JsonHttpEntity(it) },
ParameterizedTypeReference<List<DaDataAddress>>() {})
The reason is that the service that you are calling is returning a JSON array of JSON objects.

How do I deserialize json with nested breakslashes?

I have a piece of json, but when I go to deserialize it, it won't map correctly to an object in C#.
Ex:
"location": {
"raw": "{\"address1\":\"1234 Fake Street\",\"address2\":null,\"city\":\"Madison\",\"state\":\"WI\",\"zip\":\"12345\",\"country\":\"US\"}"
},
I'm using restSharp to make the api call and Newtonsoft.Json
var test = JsonConvert.DeserializeObject(content);
I've tried the following and failed:
Parsing the json
Replacing the backslashes
Serializing, then deserializing again
JavascriptSerializer
Is there anyway to deserialize a string into an object with the backslashes there?

Parsing JSON object with java object as value

I am trying to convert a JSON object to JavaScript object. JSON object i received from webservice
contain java object
{
gateway:com.admin.mypackage.addreesoftheobject;
}
JSON.parse in JavaScript, failed to parse this field, throwing exception, invalid character 'c'
is there any other way of parsing my JavaScript object.
Thanks and Regards
Biswarup
The problem is it's incorrect JSON. You can use validators for checking:
jsonlint
jsonformatter
if you change your JSON to :
{
"gateway":"com.admin.mypackage.addreesoftheobject;"
}
it should be parsed correctly.

JSON deserialization error in WebApi with array

I'm posting the following JSON payload from a JavaScript Angular app to a webapi service:
{Notes: "test", Ids: [606, 603]}
this.http.post(url, {"Notes": "test", "Ids": [606,603]}, options)
I'm attempting to deserialize this into a .net Dictionary like:
[HttpPost]
public IHttpActionResult Test(Dictionary<string,string> formData)
{
}
(I've tried to add the [FromBody] decorator too).
If I don't include the array, this works fine. But with the array, I get a couple of parse error:
Unexpected character encountered while parsing value: [. Path 'Ids', line 1, position 23.
Invalid JavaScript property identifier character: ]. Path 'Ids', line 1, position 30.
The "JSON" you're posting is not valid JSON - you can use a tool like JSONLint to validate your JSON.
The correct JSON syntax for your data is:
{
"Notes": "test",
"Ids": [606, 603]
}
Also - the method takes a Dictionary<string,string> object. Your array is not a string, and the controller will therefore fail while trying to deserialize the array into a string.
My suggestion is to create a model, which the controller method should receive. Like this:
[HttpPost]
public IHttpActionResult Test(YourModel data)
{
}
class YourModel
{
public string Notes {get;set;}
public int[] Ids {get;set;}
}
Using this code, the controller will deserialize your JSON (when you have corrected the JSON syntax problems) into an instance of YourModel.

How to pass a JSON string to API Gateway as query Parameter

How can i pass a JSON object like {val: 1} to my Lambda function as a query parameter?
Following Standardized way to serialize JSON to query string? i URL-encoded my JSON object and requested the following: mysite.com/path?json=%7B%22val%22%3A%201%7D
As requestTemplates i tried the following two options
"json": "$input.params().querystring.json"
"json": "$util.parseJson($input.params().querystring.json)"
But i got this error message:
{"message": "Could not parse request body into json: Unexpected
character (\'v\' (code 118)): was expecting comma to separate OBJECT
entries\n at [Source: [B#37a2970e; line: 1, column: 47]"}
If i do not encode the query string so: mysite.com/path?json={"val":1} i get a 400 error
Your mapping template is producing no valid JSON, you have to wrap the key/value pair in curly braces
I guess you do not want to wrap the value in quotes, it will be a string and no object otherwise
You can use $util.urlDecode to decode URL encoded strings
Your mapping template should look like this:
{"json": $util.urlDecode($input.params().querystring.json)}
For mysite.com/path?json=%7B%22val%22%3A%201%7D this mapping template will result in the following JSON:
{
"json": {
"val": 1
}
}
If you want the querystring JSON to be passed on the root level to your Lambda function use this as a mapping template:
$util.urlDecode($input.params().querystring.json)