I am using $.ajax method to get the data from the MVC controller. I am usingPOST method according to the JSON Hijacking for security standards. If I debug I am able to get the data in controller, but after returning data to the $.ajax's success function then it is showing me empty json array like below.
In controller I am using method as below:
public async Task<ActionResult> GetUsersFromOrganization(string searchString) {
string accessToken = await SampleAuthProvider.Instance.GetUserAccessTokenAsync();
var result = await graphService.GetUsersFromOrg(accessToken, searchString);
var json = JObject.Parse(result);
var valueJSON = json.GetValue("value");
return Json(valueJSON, JsonRequestBehavior.AllowGet);
}
json contains below data:
Here is the valueJSON value
The valueJSON is a JToken, Json(valueJSON) method is serializing your valueJson as a JToken class and not as the deserialized array of objects that you need, you can try to return the JToken as a string with return Content(valueJSON .ToString(),"application/json"); or parse the JToken to the original array of objects.
Related
I'm new to C# and having trouble processing queries into the desired format. If i run the code this way the response is:
["{\r\n \"Plant\": \"1195118\"\r\n}","{\r\n \"Plant\": \"1195157\"\r\n}"]
Which isn't the desired result. The actual desired output is a JSON of the following format:
{
"plant":["123235", "1195157"]
}
The code i'm using is below. I have tried several options but i'm struggling with the C# handling of JSON.
Any help would be appreciated. Thanks.
string queryString = "SELECT properties.reported.Plant_Number FROM devices WHERE properties.reported.Plant_Number != null";
IQuery query = registryManager.CreateQuery(queryString);
var json = (await query.GetNextAsJsonAsync());
return (ActionResult)new OkObjectResult(json);
The JSON you want is a single object, and the JSON you are getting is an array with one entry that is a string. In short: you need to parse the JSON.
var json = (await query.GetNextAsJsonAsync());
return (ActionResult)new OkObjectResult(json);
The first line returns an enumerable of strings, the second line returns it to the caller. So that's why the result you are getting is an array with strings.
If you want it to returns JSON instead, you will need to parse the string. To do that, you can use the JsonConvert class in the NewtonSoft.Json library (comes with your Function by default). You can learn about that here.
Edit after author's comment:
var jsonStrings = await query.GetNextAsJsonAsync();
var deviceProperties = jsonStrings.Select(JsonConvert.DeserializeObject<DeviceProperty>);
return (ActionResult)new OkObjectResult(deviceProperties);
public class DeviceProperty
{
public string Plant { get; set; }
}
Can someone explain why my JSON object isnt being correctly parsed into an Angular object? (the Angular object values are empty when I display HTML)
Angular code making request for JSON
GetMessageSub(): void {
this.http.get('http://localhost:61460/api/values')
.pipe(map(res => JSON.parse(res.toString())),
catchError(this.handleError('getMessageSub()', [])))
.subscribe(people => this.people = people);
}
C# code that is replying with a JSON
public JsonResult Get()
{
return Json("[{ id:1, name:\"value2\" }]");
}
Angular code that declares a People object
export class People {
id: number;
name: string;
}
HTML that calls the people object (which is populated by GetMessageSub()
people found: {{people.id}} -- {{people.name}}
Your C# code:
return Json("[{ id:1, name:\"value2\" }]");
returns a string, "[{ id:1, name:\"value2\" }]", encoded as JSON, so "\"[{ id:1, name:\\\"value2\\\" }]\"", not an array with a single object. If you want to do that, either:
Build an array of objects in C# and send that through JSON:
return Json(new object[] { new { id = 1, name = "value2" } });
Or send it as a string using a ContentResult:
return Content("[{ id:1, name:\"value2\" }]", "application/json");
You'd need to change the signature of your method as well for the latter option.
You are already returning a valid JSON, no need to parse, just assign
this.http.get('http://localhost:61460/api/values')
.pipe(map(res =>res)),
catchError(this.handleError('getMessageSub()', [])))
.subscribe(people => this.people = people);
I have a huge dataset of Jobject type created in following format
{
"key_1": {"id":"1", "name":"some1", ....},
"key_2": {"id":"", "name":"some2", .....}
}
I have created such object structure using following code:
JObject res = new JObject();
JObject jo = new JObject();
jo.Add("id", "1");
jo.Add("name", "some1");
res.Add("key_1", jo);
and so on;
I have a webservice method which has return type object and attributes as [WebMethod][ScriptMethod(ResponseFormat = ResponseFormat.Json)]
how to return this data as object in ajax request. I tried res.ToObject<(object)>() //added curely braces around object because of html object tag but it returns empty array collection at client side, but my expectation is get result as mentioned above (a proper object). How should i return res to get desired json output
Edited - thanks Brian
There is a difference between things you CAN do and things you SHOULD do...
The right way to return your JObjects is up to you... create real objects that represent them... create key / value pairs that can be serialized...
What you don't want to do is just write the JSON out to the response... however since that's literally what your asking... here is how you would do it.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetObject()
{
string json = GetJsonFromDatabase();
HttpContext.Current.Response.Write(json);
}
Note that your method has to return void and you are writing your json straight out to the response stream. Super dirty... super ugly... please don't do this. You'll also have to manually turn it into an object on the js side.
I have this object and would like to filter it based on the value of customer_email. For example, I only want to return commissions where the customer email is test#test.com. This is a simplified example of what a response would look like. Below is the method where I grab all the data.
public RootObject GetData(string customerEmail)
{
var data = new Commission();
using (var httpClient = new HttpClient())
{
var requestContent = JObject.FromObject(new
{
commission_id = data.id,
customer_email = customerEmail
}).ToString();
......
RootObject response = JsonConvert.DeserializeObject<RootObject>(responseContent);
return response;
}
}
When I get the response, the information looks like this:
{"response":{
"code":"200",
"message":"OK: The request was successful. See response body for additional data.",
"data":{
"commissions":
[{
"commission_id":"12345",
"customer_email":"test#test.com"
},
{
"commission_id":"67890",
"customer_email":"fake#fake.com"
}]
You can achieve it using simple LINQ right after serialization of response to RootObject.
return response
.Response.Data.Commissions
.Where(commission => commission.CustomerEmail == customerEmail);
Then you can use a lambda expression to easily filter the contents of that list.
return response.Response.Data.Commissions.Where(c => c.customerEmail==customerEmail);
This will return only the instances of Commission in the response's commissions collection.
A side effect of this solution would be changing the return type of the method from RootObject to IEnumerable<Commission>. Which would mean that callers of this method would no longer have access to any other data in the response object (besides the commissions data).
I'm trying to send a string of JSON to the client from a database for a JavaScript plugin to highlight the states it gets back. However, in addition to the state information I need, I'm also getting the variable name. Is there anyway I can correct the formatting so that instead of it looking like this:
{"statesHighilght":["California","Washington","Utah","Utah","Florida","Kansas","Utah"]}
I get this:
["California","Washington","Utah","Utah","Florida","Kansas","Utah"]
This is what my controller code looks like:
public ActionResult highlight()
{
var statesHighlight =
db.Jobs
.Select(r => r.State);
return Json(new { statesHighilght }, JsonRequestBehavior.AllowGet);
}
Pass the enumerable directly to the Json method instead of wrapping it in an anonymous object.
return Json(statesHighlight, JsonRequestBehavior.AllowGet);