Extract value from Json string in SQL Server - json

How can I extract data from this Json column without using a big function ,just using simple query
I want to extract value "Hospitality" from mypropertytype
Example:
[{"myPropertyType":{"code":"9","name":"Hospitality"},"myPropertySubType":{"code":"901","name":"Hotel"},"yourPropertyType":{"code":"9","name":"Hospitality"},"yourPropertySubType":{"code":"901","name":"Hotel"}}]

Using the package Newtonsoft.Json you can deserialize any JSON into a class.
class MyPropertyType {
int code { get; set; }
string name { get; set; }
}
JsonConvert.DeserializeObject<IList<MyPropertyType>>(sqlJsonString);

Related

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);
}
}
}

How do I deserialise json to c# that is valid json but doesn't follow a standard object pattern as it has no base parameter pair

I have the following JSON:
[{
"theme-my-login":
{
"latest_version":"6.4.7",
"last_updated":"2017-01-06T18:14:00.000Z",
"popular":true,
"vulnerabilities":
[
{
"id":6043,
"title":"Theme My Login 6.3.9 - Local File Inclusion",
"created_at":"2014-08-01T10:58:35.000Z",
"updated_at":"2015-05-15T13:47:24.000Z",
"published_date":null,
"references":
{
"url":["http://packetstormsecurity.com/files/127302/","http://seclists.org/fulldisclosure/2014/Jun/172","http://www.securityfocus.com/bid/68254/","https://security.dxw.com/advisories/lfi-in-theme-my-login/"]
},
"vuln_type":"LFI",
"fixed_in":"6.3.10"
}
]
}
},{
"other-item":
{
"latest_version":"6.4.7",
"last_updated":"2017-01-06T18:14:00.000Z",
"popular":true,
"vulnerabilities":
[
{
"id":6043,
"title":"Theme My Login 6.3.9 - Local File Inclusion",
"created_at":"2014-08-01T10:58:35.000Z",
"updated_at":"2015-05-15T13:47:24.000Z",
"published_date":null,
"references":
{
"url":["http://packetstormsecurity.com/files/127302/","http://seclists.org/fulldisclosure/2014/Jun/172","http://www.securityfocus.com/bid/68254/","https://security.dxw.com/advisories/lfi-in-theme-my-login/"]
},
"vuln_type":"LFI",
"fixed_in":"6.3.10"
}
]
}
}]
json2csharp says the object model should look like this, but that's clearly not correct
public class References
{
public List<string> url { get; set; }
}
public class Vulnerability
{
public int id { get; set; }
public string title { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
public object published_date { get; set; }
public References references { get; set; }
public string vuln_type { get; set; }
public string fixed_in { get; set; }
}
public class ThemeMyLogin
{
public string latest_version { get; set; }
public DateTime last_updated { get; set; }
public bool popular { get; set; }
public List<Vulnerability> vulnerabilities { get; set; }
}
public class RootObject
{
public ThemeMyLogin __invalid_name__theme-my-login { get; set; }
}
that I am trying to deserialise into c# classes using Json.NET, but as the top level item doesn't have a traditional name:value pair (the name effectively is "theme-my-login" and the value is the object), it's not deserialising.
Any pointers on how I can get this to deserialise? Do I need to use a custom deserialiser?
The reason I cannot use a dictionary as suggested in How can I parse a JSON string that would cause illegal C# identifiers? is that I need the value "theme-my-login" as one of the values in my model as it defines the object. I have added a second item into the json as this will be a list of items. I previously only included one to show the item structure.
You need to deserialize to List<Dictionary<string, ThemeMyLogin>> like so:
var root = JsonConvert.DeserializeObject<List<Dictionary<string, ThemeMyLogin>>>(json);
The code-generation site http://json2csharp.com/ has some limitations of which you need to be aware:
The JSON standard allows for two types of container:
The array, which is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
The object, which is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace).
If your root container is an array, http://json2csharp.com/ will auto-generate a RootObject model to deserialize each object in the array. To actually deserialize the entire array you need to deserialize to a collection of root objects such as a List<RootObject>. See Serialization Guide: IEnumerable, Lists, and Arrays.
When a JSON property corresponds to an invalid c# identifier, http://json2csharp.com/ will "helpfully" add a property to the containing type that looks like this:
public PropertyType __invalid_name__my-invalid-identifier { get; set; }
Of course this will not compile, so you need to notice any __invalid_name properties and manually fix the generated code. Options for doing this include those covered in How can I parse a JSON string that would cause illegal C# identifiers? and elsewhere:
If the property name is fixed and known in advance, rename the c# property to something valid consistent with your coding conventions and mark it with [JsonProperty("my-invalid-identifier")]. (From the answer by ken2k).
If the containing type consists entirely of variable property names with a fixed schema for their values corresponding to some type T, replace the containing type with a Dictionary<string, T>. (From the answer by L.B.)
If the containing object has a mixture of fixed and variable properties, see Deserialize json with known and unknown fields or How to deserialize a child object with dynamic (numeric) key names?.
You seem to have encountered both limitations. Working sample .Net fiddle.

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>
}

JSON array is converting to a generic list, but not converting to a generic collection. Why?

I am sending a Json Array from the client web application to asp.net webapi.
For example,
{
"SurveyId":3423,
"CreatorId":4235,
"GlobalAppId":34,
"AssociateList":[
{"AssociateId":4234},
{"AssociateId":43},
{"AssociateId":23423},
{"AssociateId":432}
],
"IsModelDirty":false,
"SaveMode":null
}
Here Associate List is a JSON Array,
Usually it will automatically serialize to a List<> object.
Using the below code ,i am posting the response to the WebApi
public IEnumerable<Associate> Post(ResponseStatus responseStatus)
{
return this.responsestatusrepository.ResponseStatusCheck(responseStatus);
}
The ResponseStatus class is shown below.
public class ResponseStatus : AppBaseModel
{
public int SurveyId { get; set; }
public int CreatorId { get; set; }
public int GlobalAppId { get; set; }
public List<Associate> AssociateList { get; set; }
}
I have changed the List<> to Collection<> as a part of my code analysis correction.
ie, public Collection<Associate> AssociateList { get; set; }
But it is always getting a null value when we are using collection instead of List. Is there any specific reason for this?
Ok, I think I will have to answer this in an indirect way.
What you are passing on to the server is an array of objects (in JSON format), but once you start processing this in C# the array of objects is now treated as a single c# object. Inside this object, your model expects one of the fields to be a Collection of Associate.
Right, when I work with JSON data similar to whats mentioned in this case - I prefer to use Newtonsofts' JOject.
So here is how I made the C# object with the JSON data you provided:
Used your model:
public class ResponseStatus
{
public int SurveyId { get; set; }
public int CreatorId { get; set; }
public int GlobalAppId { get; set; }
public Collection<Associate> AssociateList { get; set; }
}
public class Associate
{
public int AssociateId { get; set; }
}
Made a routine which takes string (the JSON data), and returns an object of type ResponseStatus:
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
---------------------------------------------------------------------
public static ResponseStatus GetResponseStatusObject(string jsonData)
{
JObject jObject = JObject.Parse(jsonData);
return jObject.ToObject<ResponseStatus>();
}
Now when I call this method and pass on the exact same JSON data which you provided, I get this:
This might not directly solve your problem, but hopefully guide you in the right direction in understanding array/object serialization when working with JavaScript/C#.
Best of luck!

use of the DataContractJsonSerializer to convert datatable to json

I want to use .Net Framework built-in library to convert my DataTable / DataSet to JSON. How is this possible.
DataTable and DataSet objects cannot be JSON serialized directly. You'll need to convert them first to something like
IDictionary<string, IEnumerable<IDictionary<string, object>>>
Once you do that, you can use JavaScriptSerializer to do the actual conversion to JSON.
Update based on your comment:
If you are trying to convert the data obtained from a SQL query into JSON, represent the data in a simple class first:
public class Employee
{
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Read the results into:
List<Employee>
Now, convert the list to JSON using JavaScriptSerializer.