convert json string into array or object - c#

I get some json data form the web which is like:
[{
"pk": 1,
"model": "stock.item",
"fields": {
"style": "f/s",
"name": "shirt",
"color": "red",
"sync": 1,
"fabric_code": "0012",
"item_code": "001",
"size": "34"
}
}, {
"pk": 2,
"model": "stock.item",
"fields": {
"style": "febric",
"name": "Trouser",
"color": "red",
"sync": 1,
"fabric_code": "fabric code",
"item_code": "0123",
"size": "44"
}
}]
How can i use it in the C# winforms desktop application. I already get this data in the form of string.
Edit:
I also try to use this way..
JavaScriptSerializer ss = new JavaScriptSerializer();
object itm = ss.DeserializeObject(responseFromServer);
It returns 'System.Object[]' but i also dont know that how i can use this.
All types of answer are welcome.

I think what your after is JSON.NET

The documentation for JavaScriptSerializer specifies that for your purpose you should use Json.NET instead.
However, if you prefer to continue to use JavaScriptSerializer you need to do the following:
JavaScriptSerializer ss = new JavaScriptSerializer();
var itm = ss.DeserializeObject(responseFromServer);
The StackOverflow thread difference-between-var-and-object-in-c-sharp describes how using var implicitly types the variable, so that it's easier to work with, where-as your code uses object, which strongly types it to an object.

Related

Select type object from json?

I have a problem with correct parse object from json query. I read something about JObject. Now i have two Model for example like Car and MotorBike. Query result is:
"Vehicles":
[
{
"Id": 1,
"title": "test",
"price": "4000",
"type": "Car"
},
{
"Id": 1,
"title": "test",
"price": "4000",
"drivingLicenseCat" "A",
"type": "MotorBike"
}
]
how can i parse to custom model by type
How much control over the JSON do you have? If you are generating the JSON out of, say, web api correctly, it would come through more like:
"Vehicles":
[
{
"Id": 1,
"title": "test",
"price": "4000",
"$type": "YourNamespace.Car, YourNamespace"
},
{
"Id": 1,
"title": "test",
"price": "4000",
"drivingLicenseCat" "A",
"$type": "YourNamespace.MotorBike, YourNamespace"
}
]
and then it would be automatically deserialized when you bring it in...
Ensure, in the model that you are serializing and sending out as JSON, that you mark it up like so:
[JsonProperty(ItemTypeNameHandling = TypeNameHandling.All)]
This will add the type names to the objects as they are serialized. I should also note, that this is with Newtonsoft as your Json library. I'm not sure about the built-in Json.

Customise Default Output Of JSON in MVC C#

I am using dynamic ExpandoObject() to create some json required for an NVD3/d3.js visualisation.
The nvd3 library is pretty explicit in what it needs with regards to data identifiers.
Exactly the json i need is the following -
[{
key: "AgeGroups",
values: [{
"label": "<20",
"value": 0
}, {
"label": ">20 <29",
"value": 160
}, {
"label": ">29 <39",
"value": 240
}]
}]
Note: the string 'key' must be lowercase and values must be pluralized.
With the following c#, I am able to get very close -
ageDemoJson.AgeGroups = new object[]
{
new { label = "<20", value = lessThan20 },
new { label = ">20 <29", value = between20and29 },
new { label = ">29 <39", value = between29and39 },
};
This outputs the following
[{
Key: "AgeGroups",
Value: [{
"label": "<20",
"value": 0
}, {
"label": ">20 <29",
"value": 160
}, {
"label": ">29 <39",
"value": 240
}]
}]
With this output, I need to customise the default behaviour of ExpandoObject and make the string 'Key' become 'key' and the string 'value' become 'values'
Is there anyway of doing this?
Of course I can work around this by parsing the json to string and replacing what I need in javascript, but would like if I didn't have to do that.
If you're using asp.net core you can change the JSON serialization by adding this line:
services.AddMvc()
.AddJsonOptions(opts =>
{
// Force Camel Case to JSON
opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
Or you can achive the same result by using Newtonsoft's Json.NET with this option:
string json = JsonConvert.SerializeObject(
yourObjectToSerialize,
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
);

Remove double curly braces while creating JObject C#

I am trying to create JsonObject with the below-mentioned structure.
{
"id": "1",
"name": "XXX",
"age": "30"
}
Using the code,
dynamic sampleJson = new JObject();
sampleJson.Add("id", "1");
sampleJson.Add("name", "XXX");
sampleJson.Add("age", "30");
But the problem is that extra curly braces is appearing at the begining and end of the json structure, as shown below.
{{
"id": "1",
"name": "XXX",
"age": "30"
}}
I use the required JSON structure as the post body of an API and it should be in the JSON format(So cant use JSON string structure using ToString() method).How can I remove the extra braces and achieve my requirement ???
Since you are using a JObject, you can simply call the ToString() override to create your JSON. For example:
JObject sampleJson = new JObject();
sampleJson.Add("id", "1");
sampleJson.Add("name", "XXX");
sampleJson.Add("age", "30");
var json = sampleJson.ToString();
Now your json variable will contain:
{
"id": "1",
"name": "XXX",
"age": "30"
}
ToString() didn't work for me. The following did:
JsonConvert.DeserializeObject(JSONStringHere, typeof(ExpandoObject));

Extract first set of records in JSON C#

I have a requirement to get the first set of records in c# JSON. Here is my JSON data for example
string sJSON = "{
{
"ID": "1",
"Name":"John",
"Area": "Java" ,
"ID": "2",
"Name": "Matt",
"Area": "Oracle" ,
"ID": "3","Name":
"Danny","Area": "Android"
}
}"
I need to extract only the 1st set of records (i.e. {{"ID": "1", "Name":"John", "Area": "Java"}}).
If there is only one record my code (see below) works fine but when there are multiple records it takes the last set of JSON data (i.e. {{"ID": "3","Name": "Danny","Area": "Android"}}).
JObject jsonObject = JObject.Parse(sJSON);
string sID = (string)jsonObject["ID"];
string sName = (string)jsonObject["Name"];
string sArea = (string)jsonObject["Area"];
Can anyone help me extract only the 1st set of JSON data?
You return the JSON data as JSON Array, now it is a simple JSON string.
If you're able to generate like below then you can easily get the single JSON element easily.
[{ "ID": "1", "Name":"John", "Area": "Java" },{ "ID": "2","Name": "Matt","Area": "Oracle" },{ "ID": "3","Name": "Danny","Area": "Android" } ]
Use the below link, to understand this JSON format.
http://json.parser.online.fr/
Parse the data as JToken.
Such that you have something like:
var jToken = JToken.Parse(sJSON);
var isEnumerable = jToken.IsEnumerable()
if(isEnumeable)
{
cast as JArray and get firstOrdefault
}
var isObject = jToken.IsObject();
if(isObject )
{
cast as JObject and perform straight casting
}

Reference Object Property with JSON.Net when property has special characters

I am using JSON.Net to update an object within an XML File. This works great! However, I need to update a property that has some special charecters in it and I can't find any information out there on how to do this with JSON.Net.
XML
<ProfileSettings>{
"Name": "Default",
"Status": "New",
"DeploymentVariants": {
"SPSite": {
"Signature": "SPSite",
"Type": "SPSite",
"Label": "SharePoint Site",
"Source": "Solution",
"DefaultValue": "http://google.com",
"Value": "http://google.com"
},
"Process/Participant[#Name=\"Manager\"]>User": {
"Signature": "Process/Participant[#Name=\"Manager\"]>User",
"Type": "SPUser",
"Label": "User for swim lane Manager",
"Source": "Swimlane",
"DefaultValue": "John Smith",
"Value": "John Smith"
}
},
"DeploymentScripts": {},
"SPList": "mySPList"
}</DeploymentProfile>
In order to update the DefaultValue in the SPSite Object, I can use JSON.Net like so:
dynamic fromSolution = JsonConvert.DeserializeObject(profileObject);
fromSolution.DeploymentVariants.SPSite.DefaultValue = txtSPSite.Text;
However, this won't be true if I'm trying to access the Process/Participant[#Name=\"Manager\"]>User object. How can I access a property when it's got special characters like this one?
fromSolution.DeploymentVariants.Process.DefaultValue did not work and obviously including special charecters within that will just result in runtime errors.
JObject implements IDictionary<string, object>. You can use dictionary syntax:
fromSolution.DeploymentVariants["Process/Participant[#Name=\"Manager\"]>User"].DefaultValue

Categories

Resources