JSON string to actual JSON - 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);
}
}
}

Related

Is there a setting to keep empty lists during JSON serialization in ServiceStack?

As the title says, is there a way to keep empty lists during JSON serialization in ServiceStack?
ServiceStack.Text JSON Serializer, already serializes empty lists by default:
using ServiceStack;
using ServiceStack.Text;
Console.WriteLine(new Test().ToJson());
public class Test
{
public List<string> List { get; set; } = new();
}
Output:
{"List":[]}

JsonConvert with number as item name

I have extracted the below json from ETH. So this is a valid json.
"networks": {
"18": {
"address": "0x478a2763d239b60206006437f5154dad59fef909"
}
}
Trying to parse using:
dynamic Obj = JsonConvert.DeserializeObject(".... json string .....");
Obj.Networks.18.address; // Error
Obj.SelectToken("networks.18.address"); // Null
I can't even compile because a label name cannot start with number.
May I know what is the correct way to access the address?
You can create a model that represents the data
public class RootObject {
public Dictionary<string, network> networks { get; set; }
}
public class network {
public string address { get; set; }
}
And use that to access the desired information
var data = JsonConvert.DeserializeObject<RootObject>(".... json string .....");
var address = data.networks["18"].address;
because of the syntax conflict, string Dictionary was used as a workaround to be able to access the key value pair.

Custom serialization in Service Stack using DeSerializeFn

In servicestack, I am trying to process a webhook which sends the following JSON body to a service stack endpoint:
{
"action": "actionType1",
"api_version": "1.00",
"data": {
"id": "a8d316b8-10a7-4440-a836-9bd354f656db",
//VARIABLE other properties / structure
}
}
Which I am trying to map to the following request object:
[Route("/public/Webhookhandler", HttpVerbs.Post)]
public class MyCustomRequst
{
public string action { get; set; }
public string api_version { get; set; }
public string data { get; set; } //Will be the remaining JSON
}
However, when the service stack framework processes this - the value in "data" is the correct part of the JSON body, but with all of the quotes removed - so it is no longer valid.
I have tried to override the serialization for the whole request object using something like this:
JsConfig<MyCustomRequst>.DeSerializeFn = DeserializeMyRequestDto;
public MyCustomRequst DeserializeMyRequestDto(string rawBody)
{
var result = rawBody.FromJson<MyCustomRequst>();
return result
}
But even in this case, the value of the "rawBody" variable is still the correct JSON data but with all the quotes removed, e.g.
{
action:actionType1,
api_version:1.00,
data:{id:a8d316b8-10a7-4440-a836-9bd354f656db}
}
Am I doing something wrong here? I am unsure whether I am trying to make service stack do something it is not intended to do, or whether I am missing something that would make this work.
Any help would be appreciated :-)
Your DTO should closely match the shape of the JSON, if it's always a flat object you can use a string Dictionary, e.g:
[Route("/public/Webhookhandler", HttpVerbs.Post)]
public class MyCustomRequst
{
public string action { get; set; }
public string api_version { get; set; }
public Dictionary<string,string> data { get; set; }
}
If it's a more nested object structure you can use a JsonObject for a more flexible API to parse dynamically.

Unable to retrieve Json data from remote server binding to object in asp.net mvc

I am developing an Asp.Net mvc application. In my application, I need to retrieve json object from remote server. I am using web client for it. But it is giving me error. My scenario is below.
I have this url
http://graph.facebook.com/{fb_id}/picture?width=200&height=200&redirect=false
When I access from browser, it return something like this
So I am trying to retrieve that data as json and then serialize them back. So I builds two classes like below to bind that data.
public class FacebookAvatarResponse
{
[JsonProperty("data")]
public FacebookAvatarData Data { get; set; }
}
public class FacebookAvatarData
{
[JsonProperty("height")]
public int Height { get; set; }
[JsonProperty("width")]
public int Width { get; set; }
[JsonProperty("is_silhouette")]
public bool IsSilhouette { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
}
In controll, I built an action method
[AllowAnonymous]
public JsonResult Test(string avatarDataUrl)
{
using (WebClient webClient = new WebClient())
{
string data = webClient.DownloadString(avatarDataUrl);
return Json(JsonConvert.DeserializeObject<FacebookAvatarResponse>(data),JsonRequestBehavior.AllowGet);
}
}
As you can see I am getting that data as json and then return as action result. But when I request that action method passing correct url as parameter, it is giving me this error.
How can I retrieve JSON data from remote server binding to the specific classes?
Possibly your are not passing JSON to DeserializeObject.
JsonConvert.DeserializeObject takes JSON value.
Check your data should be in json format to deserialize.
Json(JsonConvert.DeserializeObject<FacebookAvatarResponse>(data),
JsonRequestBehavior.AllowGet);

How to enumerate json string in MVC Razor foreach loop?

I'm using SQL Server 2016 to return json data in a string field in my data set. I passed the json string to the model without any conversions. I want to enumerate my json string field in MVC razor like:
#foreach (var notification in Model.AccountSettings.EmailNotifications)
{
EmailNotifications is a json array of objects.
EmailNotifications = [{"EmailNotificationID":8,"EmailNotificationName":"Any new KLAS report is published.","IsSet":false},{"EmailNotificationID":9,"EmailNotificationName":"KLAS publishes a report in one of my areas of interest.","IsSet":false}]
What the best way to do this?
The clean solution is to create a class to represent each item in your JSON array, convert your string to a list of this class and enumerate that.
public class NotificationItem
{
public int EmailNotificationID { get; set; }
public string EmailNotificationName { get; set; }
public bool IsSet { get; set; }
}
And you may use Newtonsoft.Json.JsonConvert.DeserializeObject method to convert the json string to list of NotificationItem objects.
#{
var items = Newtonsoft.Json.JsonConvert
.DeserializeObject<List<NotificationItem>>("yourJsonStringHere");
}
#foreach (var item in items)
{
<p>#item.EmailNotificationID</p>
<p>#item.EmailNotificationName </p>
}