How can I put JSON object in setQueryParameter parameters? - javascript

In Mobilefirst Platform 8.0, in order to send a request to an adapter procedure I can use something like this
resourceRequest.setQueryParameter("params", "['Washington', 'United States']");
But this is for 2 string values. How can I send a JSON object instead of a string?
I would like to send something like this:
var request = {name: 'George', suername: 'Williams', Id: '1234'};
resourceRequest.setQueryParameter("params", request);
If yes, what is the correct syntax?

Try the following approaches:
Pass it directly, but as a string...
resourceRequest.setQueryParameter("params", “[{’name’ : ‘bob’, ‘’age’ : 25}, 'United States']");
Create a JSONArray and pass it
JSONArray params = new JSONArray();
params.putObject(myJsonObject);
resourceRequest.setQueryParameter("params", params);

Related

how do we send file from django to reactjs where i dont need RESTFRame work?

I am new to ReactJS,I am using a django as backend, React as frontend i need to send a dict/json to reactjs which is locally created by choices not from data base. is there a way to send Data from django to reactjs without restframe work?
you can easily convert dic to json using json.dumps() method.
import json
# Data to be written
dictionary ={
"id": "04",
"name": "sunil",
"department": "HR"
}
# Serializing json
json_object = json.dumps(dictionary, indent = 4)
You can use JsonResponse instead of ordinary HttpResponse:
from django.http import JsonResponse
def hello_dictionary(request):
data = {'name': 'Alison', 'grade': 9}
return JsonResponse(data)
def hello_list(request):
data = [{'name': 'Alison', 'grade':9}, {'name': 'Alice', 'grade': 8}, {'name': 'Tom', 'grade': 10}]
return JsonResponse(data, safe=False)
If you pass something that is not a dictionary remember to add safe=false
Reference:
https://docs.djangoproject.com/en/4.1/ref/request-response/#jsonresponse-objects

Serializing a JSON object for a Django URL

I have a JSON object that looks like this:
var obj = {
"selection":[
{
"author":"John Doe",
"articles":[
"Article One",
"Article Two"
]
}
]
}
I want to pass this object to Django to render a view that displays 'Article One' and 'Article Two' upon render. I first serialize the JSON object so that it can be appended to a URL; I use $.param(obj) for serialization. Now the JSON object looks something like this:
"selection%5B0%5D%5Bauthor%5D=John+Doe&selection%5B0%5D%5Barticles%5D%5B%5D=Article+One&selection%5B0%5D%5Barticles%5D%5B%5D=Article+Two"
Now I can append this to a path and use window.open(url) the view will handle everything else. On the Django end, I was surprised to see that the structure of the JSON object has changed to this:
"selection[0][author]=John+Doe&selection[0][articles][]=Article+One&selection[0][articles][]=Article+Two"
I want to be able to use the JSON object as a dict e.g.:
obj = request.GET.get('selection')
obj = json.loads(obj)
print(obj[0].author)
...
How should I handle this JSON structure on the Django side of things?
You are not properly serializing the object to JSON, even if you say you do. The correct way would be to use JSON.stringify(), as #dunder states.
Than you parse it back to an object with JSON.parse(strignifiedJson).
var obj = {
"selection":[
{
"author":"John Doe",
"articles":[
"Article One",
"Article Two"
]
}
]
}
// Stringify and encode
var objAsParam = encodeURIComponent(JSON.stringify(obj));
// Send as a param, for example like http://example.com?obj=YourStringifiedObject...
// Parse it back:
var parsedObj = JSON.parse(decodeURIComponent(objAsParam));

Pass list of items from $.get() to MVC controller

My controller Action method looks like the below:
[HttpGet]
[Route("ShowModal")]
public Task<IActionResult> GetDetails(int id, string name, IEnumerable<Employee> employees)
{
//create a model
//Some business logic codes
return PartialView("_Partial.cshtml", model);
}
I need to call the above Action Method from jQuery's $.get() method on a button click, capture the partial view returned as HTML, and show it in a Bootstrap popup.
I am not able to pass the IEnumerable<Employee> from the jQuery method, it is always null, whatever I try.
Below is the JS code:
<a class="btn btn-primary" onclick="ShowModal();" data-keyboard="true" data-toggle="modal">ShowModal</a>
<div class="modal fade" id="divShowModalDialog" role="dialog" tabindex="-1">
<div class="modal-body" id="divShowModalBody">
</div>
</div>
function ShowModal()
{
var list = [{ Id: 101, Gender: 'MALE' }, { Id: 102, Gender: 'FEMALE' }];
list = JSON.stringify(list);
var data = { 'id': 999, 'name': 'JAMES', 'employees': list };
$.get('/Area1/Controller1/ShowModal', data)
.done(function (response) {
if (response != undefined) {
$('#divShowModalBody').html(response);
$('#divShowModalDialog').modal(
{
backdrop: 'static',
keyboard: true,
});
}
})
.fail(function (xhr) {
console.log(xhr);
})
}
I get the id and name parameter in the Action method, but the list is always empty. I have tried after removing JSON.stringify() as well, but it doesn't work.
I know I'm missing a trivial thing, please help.
First, you should be using [HttpPost] on your controller action and not [HttpGet], and of course you'll need to use post from jQuery which is using $.post() and that is because 'POST' is the correct - but not the only - HTTP verb to actually post data to the server side.
Second, you shouldn't stringify your employees list before you put it in your data javascript object that you are sending.
so, list = JSON.stringify(list); and just straight away go
var data = { 'id': 999, 'name': 'JAMES', 'employees': list };
You also might need to provide the dataType using $.post(url,data,onsucess,dataType) check documentation in the link above.
Last, on your action method remove IEnumerable<T> and replace it with a concrete collection type like List<T> because the JSON serializer will need to know which type of collection to instantiate at binding time.
Actually you can achieve it without changing it to POST by using $.ajax()
Use a dictionary object instead of IEnumerable in action method
public ActionResult GetDetails(int id, string name, Dictionary<int,string> employees)
{
And then in the script
var list = [{ Id: 101, Gender: 'MALE' }, { Id: 102, Gender: 'FEMALE' }];
var data = { id: 999, name: 'JAMES', employees: list };
debugger;
$.ajax({
url: '/Home/GetDetails',
type: "GET",
data :data,
contentType: "application/json",
dataType: "json"
});
I was replying to your comment but decided it would be easier to demonstrate my point as an answer.
To answer your question, no I am not sure. But thats why I asked you to try it first, it seems logical as you are passing a list and not IEnumerable to your function.
Also, depending on what your Employee class looks like, you should try this: (you need a constructor in your Employee class for this)
List<Employee> list = new List<Employee>();
list.Add(new Employee(101, 'MALE'));
list.Add(new Employee(102, 'FEMALE'));
var data = { 'id': 999, 'name': 'JAMES', 'employees': list };
...
Update
I realize why I'm wrong, I kept thinking in C# terms. Json.stringify() returns a json style string (which C# just sees as a string), so your public Task GetDetails(int id, string name, IEnumerable employees) should be public Task GetDetails(int id, string name, string employees) and then in C#, you need to parse the JSON string. A helpful link:
How can I parse JSON with C#?

convert json object to serialized string for server side processing?

I'm trying to convert a returned json object into a serialized string that I can process further with some PHP server side code:
The returned object looks like this:
Object {id: "123456787654321", email: "some-email#gmail.com", first_name: "First", gender: "male", last_name: "Last"}
I can convert the object to a string with the following:
var paramString = JSON.stringify(response);
console.log(paramString);
// doesn't work
//var params = paramString.serialize();
How do I now convert the string to a serialized string that I can pass to my server with the following client side call:
I would expect something like this:
id=123456787654321&email=some-email#gmail.com&first_name...
My server side code:
$.post("/functions/test_functions.php", {params: params}, function(data) {
...
}, "json");
I handle the params array like this server side:
$vars = $_SERVER['REQUEST_METHOD'] === "GET" ? $_GET : $_POST;
$params = array();
isset($vars['params']) ? parse_str($vars['params'], $params) : null;
You can pass JSON-string to server and decode it with json_decode(). See http://php.net/manual/en/function.json-decode.php for details.
Unless there's a specific reason for stringifying, you don't actually need to. jQuery .post will handle the serialization for you, for example:
var response = {id: "123456787654321", email: "some-email#gmail.com", first_name: "First", gender: "male", last_name: "Last"};
$.post("/functions/test_functions.php", response, function(data) {
...
}, "json");
Will make a POST request like this:
/functions/test_functions.php
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Form Data: id=12345654321&email=some-email#gmail.com&first_name....

JavaScript to Handle REST JSON Feed

Trying to figure out the JavaScript syntax for handling JSON feed returned by a REST service. Suppose a random REST service (e.g. http://random.service/directory) is returning the following feed:
{
'firstName': 'John',
'lastName': 'Smith',
'address': {
'streetAddress': '21 2nd Street',
'city': 'New York'
}
}
and that I have a JSON parsing JS function (to parse the above feed) like:
function parseRESTFeed(json) {
...
}
How do I bridge the REST call of "http://random.service/hello" to parseRESTFeed(json) via JS?
Much Thanks!
If you use jQuery (and you should if you don't), then you can do it like this (ref):
$.getJSON('http://random.service/directory', null, function(data){
// And here you can do whatever you want with "data", no need to parse it
alert(data.firstName);
});
If you have some other way to get response from the service as string, again there is no reason to parse, since you can use javascript's eval. For example:
var myJSON = "{'firstName': 'John','lastNAme': 'Smith'}";
var data = eval('(' + myJSON + ')');
alert(data.firstName);

Categories