How do I deserialize json with nested breakslashes? - json

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?

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 to Deserialize a JSON and serialize a specific String value pair as different JSON?

The Json body I want to deserialize is something like below
{
"status": "OK",
"place_id": "07e0a63d862b2982e4c4b7e655f148d2",
"scope": "APP"
}
Below is the Json body I want to build from above Json after deserializing it
{
"place_id": "07e0a63d862b2982e4c4b7e655f148d2"
}
Because your JSON data appears to be rather small you could use Gson's JsonParser.parseString(String) method to parse the data into an in-memory representation, then copy the relevant JSON object member to a new JsonObject and serialize that to JSON using Gson.toJson(JsonElement):
JsonObject original = JsonParser.parseString(json).getAsJsonObject();
JsonObject copy = new JsonObject();
// Might also have to add some validation to make sure the member
// exists and is a string
copy.add("place_id", original.get("place_id"));
String transformedJson = new Gson().toJson(copy);
If this solution turns out to not be efficient enough for you, you could also have a look at JsonReader and JsonWriter.

How to convert ManagedCursorStreamProvider to JSOn object in mule 4

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.

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 response parsing using JavaScript Overlay Types in GWT

I have a query in parsing json response coming from server. We have used gson to serialize a list of objects to a json string in server. In gwt client, we have used JavaScript overlay types to parse it. So my gwt call from client looks like this
//Code snippet where json response is from list of obj from server.
jsonpReqBuiler.requestObject(url, new AsyncCallback<JsArray<MyJsoClass>>() {
onSuccess(final JsArray<MyJsoClass> result) {
////Need a string equivalent of JsArray type to sore???
}
}
We want to store the json response - JsArray into sqllite database as a string. Even though server responds with Json string, it has resulted as JsArray type after internal parsing, now I can store it as a string so that I can read and convert back??
You can use following code:
jsonpReqBuiler.requestObject(url, new AsyncCallback<JsArray<MyJsoClass>>() {
onSuccess(final JsArray<MyJsoClass> result) {
String json = new JSONArray(result).toString();
}
}