Receiving JSON in salesforce - json

I am trying to receive a JSON string in salesforce by converting a blob in the body of an Http request. However, when I convert the blob to a string there are \ characters that get inserted into the request which prevents me from parsing.
I then tried to take the string and remove all \ characters... that didn't work either.
RestRequest req = RestContext.request;
Blob jsonBlob = req.requestBody;
String jsonString = jsonBlob.toString();
return jsonString;
The original string (the one that is received as a blob) looks like this:
{"putTimeCard":{"timecard":{"timeCardID": "","employeeID": ""}}
And after converting to a salesforce string and assigned to the jsonString is altered to:
{\"putTimeCard\":{\"timecard\":{\"timeCardID\": \"\",\"employeeID\": \"\"}}
Has anyone found a solution for this?
Thanks

The JSON Deserializer can parse the string with the escape characters. You can either deserialize into an object like so:
String jsonString = '{\"putTimeCard\":{\"timecard\":{\"timeCardID\": \"\",\"employeeID\": \"\"}}}'
Timecard t = (Timecard) JSON.deserialize(jsonString, Type.forName('Timecard'));
or if you just want a map of objects you can do the following:
String jsonString = '{\"putTimeCard\":{\"timecard\":{\"timeCardID\": \"\",\"employeeID\": \"\"}}}'
Map<String, Object> m = (Map<String, Object>) JSON.deserializeUntyped(jsonString);

Related

Convert String to Json in Ballerina

Is there a way to convert string to json in Ballerina ?
I found this PR - Add jsons:parse() method to get a JSON from a string where it says adding support to parse string to json, but couldn't find any example.
I tried the following:
string person = {"name":"John", "address":{"number":89, "street":"main street", "town": "Colombo"}};
json personJson = sons:parse(person);
But it gave me an error:
undefined package 'jsons'
undefined function 'parse'
The correct way to convert a string to json in ballerina is to use the readJson function from StringReader. What you have tried was an old approach which is no longer supported.
Following example shows how this could be done using the StringReader.
import ballerina/io;
public function main(string... args) {
string str = "{\"name\":\"John\", \"address\":{\"number\":89, \"street\":\"main street\", \"town\":\"Colombo\"}}";
io:StringReader sr = new(str, encoding = "UTF-8");
json j = check sr.readJson();
io:println(j);
}
More info about StringReader can be found from the docs at - https://ballerina.io/learn/api-docs/ballerina/io.html#StringReader
From Ballerina swan lake onward, you can use the fromJsonString() method to convert a string to json:
string jsonStr = "{\"key\": \"value\"}";
json|error converted = jsonStr.fromJsonString();
if (converted is error) {
io:println("Error in parsing json");
} else {
io:println(converted);
}

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)

deserialize json to general object (without predefined schema)

I'm trying to use json.net.
I'd like to get a string (in json format) and convert it to general json object, without predefined schema.
somelting like
var jsonString = #"{\""id\"": 1,\""name\"": \""A green door\""}";
var jsonMessage = JsonConvert.DeserializeObject<JObject>(jsonString);
var myValue = jsonMessage["name"]
Is that something doable? didn't make it work
Your string is malformed, try this string instead:
var jsonString = "{\"id\": 1,\"name\": \"A green door\"}";
You could also shorten this a little bit:
string name = JObject.Parse(jsonString)["name"].ToObject<string>();

How to Convert JsonValue to JSONObject

I m using Jaql to manipulate data(data stored in json converted to string). The output for Jaql will be a com.ibm.jaql.json.type.JsonValue. It can be stored into string through toString() method. I got to do some json manipulations on the returned value. Problem here is, the output is not actual simple JSONObject. Is there a way to transform my string or JsonValue to JSONObject???
Please help.
Just use the String constructor of JSONObject:
JSONObject json = new JSONObject(jsonString);

Error while using Newtonsoft.Json to parse a Json string

My JSON string looks like this. Please note that it has escape characters.
string json = "\"{\\\"Status\\\":true,\\\"ID\\\":24501}\"";
When I use the Parse method like below I run into an error stated below:
JObject o = JObject.Parse(json);
Error reading JObject from JsonReader. Current JsonReader item is not an object: String
How do I get rid of this error or is there any other method to parse my json string and fetch the values?
Remove first and last quotes:
string json = "{\"Status\":true,\"ID\":24501}";
See the Json format here.
It seems like your object is double encoded. Try:
string json = "{\"Status\":true,\"ID\":24501}";
You need something like this
json = json.Replace(#"\", string.Empty).Trim(new char[]{'\"'})
in here format should be something like this:
string jsonNew = #"{'Status': True,'ID': 24501 }";
As SolarBear says in his comment, the problem is double-escaping.
To get the proper format, like this:
string json = "{\"Status\":true,\"ID\":24501}";
Do something like this:
json = json.Replace("\\\\", "\\");
Had similar issue today. My solution to this is contained in this extension method (using c#):
public static class StringExtensions
{
public static string RemoveDoubleEncoding(this string text)
{
if(string.IsNullOrEmpty(text))
return string.Empty;
var result = text.TrimStart('\"').TrimEnd('\"');
result = result.Replace(#"\", string.Empty);
return result;
}
}