I'm facing an issue when converting ODATA string into JSON while posting on my Dynamics CRM.
When I'm trying to serialize that way:
var phoneCallAssociationJsonData = '{'
+'"#odata.id" : "https://contoso.crm4.dynamics.com/api/data/v8.1/phonecalls('+ phoneCallUid +')"'
+'}';
And serialize it in the request like that: JSON.stringify(phoneCallAssociationJsonData);
I get a BAD REQUEST response. But When I use POSTMAN to post data and I copy the following JSON:
{"#odata.id" : "https://contoso.crm4.dynamics.com/api/data/v8.1/phonecalls(12a59ec0-76b5-e611-80ed-5065f38a8ad1)"}
It works perfectly.
Does someone know if there is a special way way to serialize string with odata format ?
I've tried to create a javascript object but adding a object.#odata.id is not possible because # is not an allowed character.
Firstly, rather than creating a string, which you then stringify, create an OBJECT
var phoneCallAssociationJsonData = {
"#odata.id" : "https://contoso.crm4.dynamics.com/api/data/v8.1/phonecalls("+ phoneCallUid +")"
};
then
JSON.stringify(phoneCallAssociationJsonData);
should now work
Related
I am afraid I don’t understand what "serializing" means. If someone can explain I’d be grateful. I am serializing a Django model in Json as explained in the Django Docs:
data = serializers.serialize("json", MyModel.objects.all())
In my HTML/JS I access the data as recommended:
{{ data|json_script:"data" }}
var myData = JSON.parse([document.getElementById('data').textContent]);
But instead of being an Object myData is a string. So I guess somehow I serialize twice or something.
I found a solution, JSON.parse works as expected on my data now:
data = json.loads(serializers.serialize("json", CoursePage.objects.child_of(self).live().public()))
But I guess I still don’t understand the meaning of "serializing" properly. The Python docs say about json.loads(s): "Deserialize s (a str instance containing a JSON document). Why do I have to deserialize before JSON.parse works? The description for JSON.parse states: "The JSON.parse() method parses a JSON string"? Which I thought Djangos serializer would gave me in the first place. I am confused.
The json_script filter is for Python objects. But serialization is already the conversion of Python objects into JSON. So effectively you're converting it twice.
In your case I wouldn't bother with that filter. Just remove the json.loads and output the data directly where you need it:
var myData = JSON.parse("{{ data|safe }}");
I am writing a web application to exchange contact information fast via QR.
I use a QR api wich is formatted like this:
`http://api.qrserver.com/v1/create-qr-code/?data=MyData&size=400x400`
I have json data formatted in a string, example of output:
`http://[myapp-url]/RecieveContact.html?Name=John%20Diggle&Title=IT%20Consultant&Organisation=testcomp&Telwork=0498553311&Telhome=&Gsm=0498553311&Email=testemail#mail.be&Website=www.testwebsite.be&Birthdate=24/04/97&Addresswork=&Addresshome=`
JSON data:
{"Name":"John Diggle",
"Title":"IT Consultant",
"Organisation":"testcomp",
"Telwork":"0498818587",
"Telhome":"",
"Gsm":"0498818587",
"Email":"testemail#mail.be",
"Website":"www.testwebsite.be",
"Birthdate":"24/04/97",
"Addresswork":"",
"Addresshome":""}
The problem is when you put this url in the QR generator it only recognises the Name parameter. I understand why this happens.
The question is is there a way using javascript to convert all this data in a string and convert it back on the recieving end?
Or does anyone know another potential fix for this problem?
You need to URL encode data with special characters you put into a URL:
var url = 'http://[myapp-url]/RecieveContact.html?Name=John%20Diggle&Title=IT%20Consultant&Organisation=testcomp&Telwork=0498553311&Telhome=&Gsm=0498553311&Email=testemail#mail.be&Website=www.testwebsite.be&Birthdate=24/04/97&Addresswork=&Addresshome=';
var query = 'http://.../?data=' + encodeURIComponent(url) + '&size=400x400';
This way you can represent characters like & inside a query string.
I have problem with send data between my two apps. I serialize data to JSON in C# using this code:
public static string SerializeToJson<T>(this T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
byte[] array = ms.ToArray();
return Encoding.UTF8.GetString(array, 0, array.Length);
}
and then i send this using socket communication to my second application which is implemented in TypeScript. I deserialize it using:
JSON.parse
function and it works fine, but if in data is special characters for example 8211 '–' it throw exception
SyntaxError: Unexpected token in JSON at position 907
Maybe it is problem with different encoding with serialize and deserialize, but I don't know which encoding is used in JSON.parse.
Anyone can help me?
An alternative is to use Newtonsoft Json.Net (available from nuget).
It's easy to use and very powerfull.
public static string SerializeToJson<T>(this T obj)
{
return JsonConvert.SerializeObject(obj);
}
And you can even add some formating or what you want.
I resolve this problem using convert to base64 my string and then decode it in my second application.
The following code worked for me. The following solution also ensures the type of underlying objects. To Convert C# object to typescript object.
Convert your object to json format using any of the JSON libraries. (newtonsoft is most suggested one)
string output = JsonConvert.SerializeObject(product); // product =new Product(); <= Product is custom class. substitute your class here
Pass this string to your application. (ActionResult or ajax call)
Now in the javascript access the value using Model (Razor or ajax result)
YourTSClass.ProcessResults('#Model') // using razor in js
or
.done(response => {ProcessResults(response)}) // using ajax success result
You need not apply JSON.Parse this way.
In the typescript you can get the result by declaring the function like this.
public static ProcessResults(result: Product){...}
I've problem with serializing object using JSONRenderer.
I'm using django-rest-framework and I've serialized object:
pk = kwargs['pk']
tube = Tube.objects.get(id=pk)
serialized_tube = TubeSerializer(tube)
serialized_tube.data looks like this:
{'id': '11122211133311'}
Unfortunately I can't serialize this using JSONRenderer, because the code
tube_json = JSONRenderer().render(serialized_tube.data)
return Response(tube_json)
gives following error
b'{"id":"11122211133311"}' is not JSON serializable
whereas
tube_json = json.dumps(serialized_tube.data)
return Response(tube_json)
works well...
I'm using Python3.4.3
The issue is not in your JSONRenderer() line, but in the line below it where you return it as a Response.
Django REST framework provides a custom Response object that will automatically be rendered as whatever the accepted renderer was, converting native Python structures into a rendered version (in this case, JSON structures). So a Python dictionary will be converted to a JSON object, and a Python list will be converted to a JSON array, etc.
Right now you are serializing your data to a JSON string then passing it to Response, where you are expecting it to be re-serialized into JSON. You can't serialize a string into JSON (you need an object or array wrapping it), which is why you are seeing the error.
The solution is to not call JSONRenderer ahead of time, and just pass the serializer data to Response.
#SOLVED
As explained by James M. Lay, I should change my content-type from application/x-www-form-urlencoded to application/json
it implied in an error because it seems that only UrlEnconded types generates POST arrays in server side (at least in PHP). So I had to change the way I receive/deal with the request in my server script
$json = file_get_contents('php://input'); //yes. php://input
if($json) $params = json_decode($json,true);
else $params = $_POST;
I also had to make a few changes in the Javascript code to check the content-type and generate different strings. If it's JSON I just use JSON.stringify
//string to use in the 'send' method
this.getParametersString = function(){
if(this.contentType == 'application/json'){
return JSON.stringify(this.parameters);
}else{}
}
I got a question
I`m building a function that receive parameters to write a list of parameters and send it by POST
The problem is that we can't send special characters, such is +
So I tried to use the function encodeURIComponent to encode them to a URI friendly string.
There comes another problem: if the parameter received is an object, I am loop through the attributes, checking if it is another object or a string, if it is an object, loop again, otherwise encode it.
But it is returning an object of encoded strings. I have to make the object become a string to send it, and for that purpose I use JSON.stringify. It decodes the encoded string. So %2B becomes + again and It is not sent to the server via POST.
on the other hand If I use stringify first and the encodeURIComponent it generates signs like " and { } that shouldn't be encoded and the string is not a well written JSON
How do you that? Is that a way without using jQuery? Do I have to build my own stringify function?!
im using the following and i have no issues
encodeURIComponent(JSON.stringify(object_to_be_serialised))