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);
Related
I am writing a Web API with requirement where need to pass result class property values as array of Json in response of GET request.
Property class which will be passed as a actual result with Ok Status with object. ( I am mocking actual requirement)
public class ABC
{
public string Name {get;set;}
public string Address{get;set;}
}
I am following default JSONfor matter option which are available in dotnet core web api and it is converting all class attribute into single json element.
{
"Person" :
[
{
"Name": "ABCD",
"Address": "INDIA"
}
]
}
My requirement is to have data in Json format with array as below -
{
"Person" :
[
{"Name": "ABCD"},
{"Address": "INDIA"}
]
}
using Newtonsoft.Json;
use this method to convert obj to string:
JsonConvert.SerializeObject(object)
use this method to convert string to obj:
JsonConvert.DeserializeObject(string)
=== Updated my answer to reflect clarified details ===
Solution with Json.Net:
To get the JSON result that you're looking for, you'll need to create a custom serializer or build your JSON object with dynamic JTokens.
Here's an example using a dynamic JObject:
https://dotnetfiddle.net/EyL5Um
Code:
// Create sample object to serialize
var person = new ABC() { Name = "ABC", Address = "India" };
// Build JSON with dynamic JTokens
dynamic jsonObj = new JObject();
var token = new JArray();
token.Add(new JObject(
new JProperty("Name", person.Name)));
token.Add(new JObject(
new JProperty("Address", person.Address)));
jsonObj.Person = token;
// Print result to console
Console.WriteLine(jsonObj.ToString());
Note
In this form, the code above is not a scalable solution. But it should provide you with a starting point to then build up an iterative approach for the data you're working with.
References
Newtonsoft Documentation - Create JSON w/ Dynamic
I am using .NET 4.7, C#, JSON.NET, MVC 5
I have some input JSON:
[
{
"id" : 1
},
{
"id" : 2
},
{
"id" : 3
}
]
This is provided by a 3rd party API
Normally I would use code such as, to deserialize:
var content = await response.Content.ReadAsStringAsync();
JObject json = JObject.Parse(content);
orderList = JsonConvert.DeserializeObject<OrderList>(json.ToString());
However I am finding that:
JObject json = JObject.Parse(content);
Crashes out with the JSON in question. I strongly suspect that the surrounding "[" and "]" is the cause.
I would normally add :
{
items: [
to correct the input JSON.
Is there a better way, to deserialize it, as it seems this input JSON is incomplete although when I test it, it does seem to be valid JSON.
Possibly I should be using JArray instead of JObject?
Thanks in advance.
You are missing commas "," in the JSON. It should be like this:
[
{
"id" : 1
},
{
"id" : 2
},
{
"id" : 3
}
]
And you can deserialize it like that:
var content = await response.Content.ReadAsStringAsync();
var list = JsonConvert.DeserializeObject<List<MyClass>>(content);
Where list is a List<MyClass>
public class MyClass
{
public int id { get; set; }
}
You have 3 options:
Instead of JObject.Parse, use JArray.Parse because the JSON is an array, not an object. This is not the best way to achieve what you want.
Deserialise to a List<T> where T is a concrete class that contains the matching properties of the object. for example:
var result = JsonConvert.DeserializeObject<List<Order>>(json);
This is better, but...
The best option is not to read the HttpClient response as a string in the first place and let the framework do the work for you. You should use the ReadAsAsync<T> extension method. Internally, this uses a stream and is more efficient than first going to string. So for example:
List<Order> orders = await response.Content.ReadAsAsync<List<Order>>();
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.
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);