Convert Json to Object in Angular 7 - json

This is json string {"firstName":"John" ,"lastName":"Doe" }.
I would like to convert json string to object with custom name in angular.This is c# code.
public class Example
{
[JsonProperty("firstName")]
public string FName { get; set; }
[JsonProperty("lastName")]
public string LName { get; set; }
}

Just use JSON.parse
console.log(JSON.parse('{"firstName":"John" ,"lastName":"Doe" }'))
But you shouldn't have to. How are you getting the JSON string? If you made a call to your C# api with the HttpClient like
http.get<YourModel>('apiUrl');
The response from the api should already be parsed as long as the api responded with a content type of text/json.

If you have a front-end model, use the classToPlain method of the lib class-transformer https://github.com/typestack/class-transformer
Example
import { classToPlain } from "class-transformer";
...
var yourModel: YourModel = {"firstName":"John" ,"lastName":"Doe" };
this.http.post(`${url}/AnyMethod`, classToPlain(yourModel)).pipe();
...
class YourModel{
firstName: string;
lastName: string;
}

Related

JSON as data type in ASP.Net Core 3.1 controller

I'm creating an Api using .Net Core 3.1 in which I need one property input as JSON in the controller, something like:
{
"name": "test",
"JSONData": { "roles": ["data1", "data2"] }
}
so that I can define the request something like:
public class MyRequest
{
public string Name { get; set;}
public JSON JSONData { get; set; }
}
I'm thinking of having it as a string and using Serialize/Deserialize it if we cannot have it as a "JSON" data type.
Is there a way to have a property as JSON type from both request and response?
I've just tried with JsonElement and could see it works; only one issue that the property is not showing up from the swagger UI. So the request is like:
public class MyRequest
{
public string Name { get; set;}
public JsonElement JSONData { get; set; }
}

JSON string to actual JSON

Using .Net core 2.2, I am building an API that returns JSON data from my stored procedure (using FOR JSON PATH), I return a value that looks like:
[{"ID":213,"SizeCode":"Small"},{"ID":257,"SizeCode":"S/M"},{"ID":214,"SizeCode":"Medium",},{"ID":215,"SizeCode":"Large"}]
So when I map it to my object to return from the API
public class Details
{
public string SizeChart { get; set; }
}
,it returns this:
"[{'ID':213,'SizeCode':'Small'},{'ID':257,'SizeCode':'S/M'},{'ID':214,'SizeCode':'Medium',},{'ID':215,'SizeCode':'Large'}]"
I don't want the double quotes around it, so I figure the actual property shouldn't be a string. Is there a better data type to use or a way to return without the double quotes?
You need to parse string into JSON object (actually in your case - JArray as it is an array) and return it from your API:
JArray a = JArray.Parse(jsonString);
So it might look like
public class Details
{
public string SizeChart { get; set; }
public JArray SizeChartJArray {
get {
return JObject.Parse(SizeChart);
}
}
}

POST json into WCF service returning (400 BAD request)

I Trying to POST a json data into self hosted WCF service
POST is working good when json string such as
{"data": "testdata"}
same POST is doesn't working and returning 400 (Bad Request) error message when json string as
{data: [{
data1: "testvalue1",
data2: "testvalue2",
data3: "testvalue3",
data4: "testvalue4",
}]
}
And this is my WCF service Code
<OperationContract>
<WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json, RequestFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Wrapped)>
Private Function DoWork(ByVal data As string) As system.servicemodel.channels.message
// DO SOMETHING WITH DATA
end function
What is difference between json string and nested json string in my case
And how can i solve my problem
Thanks.
WCF cannot deserialize complex object represented in json into string. In order to make the example work you need to accept a collection of complex objects in operation
//complex object class
[DataContract]
public class DataModel
{
[DataMember(Name = "data1")]
public string Data1 { get; set; }
[DataMember(Name = "data2")]
public string Data2 { get; set; }
[DataMember(Name = "data3")]
public string Data3 { get; set; }
[DataMember(Name = "data4")]
public string Data4 { get; set; }
}
private Message DoWork(List<DataModel> data)

Cannot Get JsonConvert.DeserializeObject with oData to Work

I a class that looks like so:
public class AccountAddress
{
[Key]
public int accountNumber { get; set; }
public int rowNumber { get; set; }
public string civicaddress { get; set; }
public AccountAddress()
{
//Default constructor
}
}
There is a rest API that returns a List of AccountAddress as oData that looks like this to a variable "result":
{
"#odata.context":"http://localhost:52139/odata/$metadata#WEB_V_CIVIC_ADDRESS/Values.Classes.Entities.AccountAddress","value":[
{
"#odata.type":"#Values.Classes.Entities.AccountAddress","accountNumber":123456,"rowNumber":0,"civicaddress":"123 FAKE EAST DRIVE"
},{
"#odata.type":"#Values.Classes.Entities.AccountAddress","accountNumber":123457,"rowNumber":0,"civicaddress":"123 FAKE WEST DRIVE"
}
]
}
When I try to use:
var addressAccountLookup = Newtonsoft.Json.JsonConvert.DeserializeObject<List<AccountAddress>>(result);
I get an error
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ATPublicTAX.Regina.ca.Values.Classes.Entities.AccountAddress]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Any help on this would be greatly appreciated.
Thanks.
You're passing the entire object to your deserialization method. You need to pass only the array, which is what it's asking you to do.
JArray array = (JArray) result["value"];
var addressAccountLookup = Newtonsoft.Json.JsonConvert.DeserializeObject<List<AccountAddress>>(array);
Something like that should work.
The solution that I got to work is create a class:
private class oDataResponse<T>
{
public List<T> Value { get; set; }
}
Then deserialize like this:
var oDataRespone = Newtonsoft.Json.JsonConvert.DeserializeObject<oDataResponse<AccountAddress>>(result);

Deserializing JSON with JSON.NET in Windows 8 Store App

I'm trying to deserialize the following JSON into an object in my Win 8 app:
{
"success":true,
"pharmacies":[
{
"name":"Test Pharmacy",
"phone":null,
"description":"sample description",
"pharmacyid":"1234567",
"pic":"/1341864197.png",
"address":"211 Warren St., #205",
"city":"Newark",
"state":"NJ",
"zipcode":"07103",
"delivery":true,
"dob_check":false,
"name_check":false,
"can_pickup":true,
"barcode_template":"9999999XX"
}
]
}
This is the model I'm using:
public class PharmacyList
{
public List<Pharmacy> pharmacies { get; set; }
}
public class Pharmacy
{
public string pharmacyid { get; set; }
public string name { get; set; }
public string phone { get; set; }
}
And here is the code I'm using to de-serialize
json = await results.Content.ReadAsStringAsync();
List<PharmacyList> p = JsonConvert.DeserializeObject<List<PharmacyList>>(json);
I'm getting the following exception:
: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[PharmacyHC.Models.PharmacyList]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Am I trying to deserialize into the wrong type or should I format the JSON as it comes back from the API differently?
I just realized the dumb mistake I made. p should have been declared as type PharmacyList instead of a list object since the class declaration for PharmacyList contained a List object already.
List<PharmacyList> p = JsonConvert.DeserializeObject<List<PharmacyList>>(json);
it should have been
PharmacyList p = JsonConvert.DeserializeObject<PharmacyList>(json);