I have my JSON in a string. How can I use JavascriptSerializer to deserialize it and find the value of SSOID?
{
"Addresses": [
{
"Address": "123 Test Road",
"State": "Mississippi"
}
],
"Birthdate": "April 12 2012",
"CreateDate": "April 13 2012",
"IDs": [
{
"isDefault": false,
"PurchaseID": "883"
}
],
"Sex": "Male",
"SSOID": 23444,
"Suffix": null,
"BoardID": 4324
}
In this particular case:
string s = "your json string";
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
var obj = js.DeserializeObject(s) as Dictionary<string,object>;
int ssoid = (int)obj["SSOID"];
var js = new JavaScriptSerializer();
var deserialized = (Dictionary<string, object>) js.DeserializeObject(json);
var ssoid = (int) deserialized["SSOID"];
var SSOID = new JavaScriptSerializer()
.Deserialize<Dictionary<string, object>>(json)["SSOID"];
OR
dynamic jObj = new JavaScriptSerializer().DeserializeObject(json);
var SSOID = jObj["SSOID"];
Related
I'm reading my json file from and trying to replace the property values. JSON file is below.
{
"fields": {
"summary": "summaryValue",
"project": {
"key": "projectValue"
},
"priority": {
"name": "priorityValue"
},
"Requestor": {
"name": "RequestorValue"
},
"issue": {
"name": "issueValue"
},
"labels": "LabelValue",
"customfield_xyz": "customfield_xyzValue"
}
}
How can I replace the value for each item inside the fields property ?
for ex:
{"fields": {
"summary": "NewsummaryValue",
"project": {
"key": "NewprojectValue"
},
"priority": {
"name": "NewpriorityValue"
}
}
}
Below is the code to parse my json file,
StreamReader r = new StreamReader(filepath);
var jsondata = r.ReadToEnd();
var jobj = JObject.Parse(jsondata);
foreach (var item in jobj.Properties())
{
\\replace code
}
I do not know exactly what you want. But I changed the json information in the code snippet as you wanted.
dynamic dataCollection = JsonConvert.DeserializeObject<dynamic>(jsonData);
string summary = dataCollection["fields"]["summary"];
string project = dataCollection["fields"]["project"]["key"];
string priority = dataCollection["fields"]["priority"]["name"];
dynamic json = new JObject();
json.summary = summary;
json.project = project;
json.priority = priority;
dynamic jsonRoot = new JObject();
jsonRoot.fields = json;
Console.WriteLine(jsonRoot.ToString());
output:
I want to map JSON path properties from key-value pairs to generate the JSON object in C# where the path contains nested array index path
Input:
Dictionary<string, string> properties = new Dictionary<string, string>();
properties.put("id", "1");
properties.put("name", "sample_name");
properties.put("category.id", "1");
properties.put("category.name", "sample");
properties.put("tags[0].id", "1");
properties.put("tags[0].name", "tag1");
properties.put("tags[1].id", "2");
properties.put("tags[1].name", "tag2");
properties.put("status", "available");
Output:
{
"id": 1,
"name": "sample_name",
"category": {
"id": 1,
"name": "sample"
},
"tags": [
{
"id": 1,
"name": "tag1"
},
{
"id": 2,
"name": "tag2"
}
],
"status": "available"
}
Using Jackson's JavaPropsMapper it can easily be achieved like:
JavaPropsMapper javaPropsMapper = new JavaPropsMapper();
JsonNode json = javaPropsMapper.readMapAs(properties, JsonNode.class);
How to implement this idea in C# so that I am able to generate the JSON object from the given JSON path node.
you can create anonymous object an serialize
var values = new {
id = "id",
name = "name",
category = new { id = 1, name = "sample"},
tags = new { id = 0, name = "sample" },
status = "available"
};
string json = JsonConvert.SerializeObject(values);
I got a JSON string with an array like this:
{
"Id": 123,
"Username": "Sr. X",
"Packages": [
{
"Name": "Cups",
"SupplierId": 1,
"ProviderGroupId": 575,
"SupplierName": "Foo Cups"
},
{
"Name": "Pins",
"SupplierId": 5,
"ProviderGroupId": 1082,
"SupplierName": "Foo Pins"
}
]
}
and I want to add a new field into Packages array like:
"Packages": [
{
"Name": "Cups",
"SupplierId": 1,
"ProviderGroupId": 575,
"SupplierName": "Foo Cups",
"New Field": "Value"
},...
Right now I can add a new field but in the main object, I'm using Json.NET library to do the job, but it seems that the documentation doesn't reach that level.
Have any one of you done it before?
JObject implemets IDictionary.
var jObj = JObject.Parse(json);
foreach(var item in jObj["Packages"])
{
item["New Field"] = "Value";
}
var newjson = jObj.ToString(Newtonsoft.Json.Formatting.Indented);
Try
JObject root = (JObject) JsonConvert.DeserializeObject(File.ReadAllText("products.json"));
JArray packages = (JArray) root["Packages"];
JObject newItem = new JObject();
newItem["Name"] = "Cups";
// ...
packages.Add(newItem);
Console.WriteLine(root); // Prints new json
I am trying to convert a JSON array to an Object. This is a hacked way but good enough for my purpose.
Basically I am writing a method to get this
var data = [{
"MonthYearShortName": "Sep-13",
"TotalCustomers": 1905.0,
"Aquisition": 317.0,
"Attrition": 9.0
}, {
"MonthYearShortName": "FY-14",
"TotalCustomers": 2158.0,
"Aquisition": 401.0,
"Attrition": 15.0909090909091
}]
into something like this
data = [{
key: 'Attrition',
color: '#d62728',
values: [{
"label": "Sep-13",
"value": 9
}, {
"label": "FY-14",
"value": 15.0909090909091
}]
},
{
key: 'Total Customer',
color: '#1f77b4',
values: [{
"label": "Sep-13",
"value": 1905
}, {
"label": "FY-14",
"value": 2158
}]
},
{
key: 'Aquisition',
color: '#1f7774',
values: [{
"label": "Sep-13",
"value": 317
}, {
"label": "FY-14",
"value": 401
}]
}
];
The colors will be static for now. I will be handling it later.
Now getting to my hacked way of getting this (this is crude I know)
I tried something like this to just get the attrition out
var data = #"[{""MonthYearShortName"": ""Sep-13"",""TotalCustomers"": 1905.0,""Aquisition"": 317.0,""Attrition"": 9.0}, {""MonthYearShortName"": ""FY-14"",""TotalCustomers"": 2158.0,""Aquisition"": 401.0,""Attrition"": 15.0909090909091}]";
JArray a = JArray.Parse(data);
var label1 = a[0]["MonthYearShortName"].ToString();
var label2 = a[1]["MonthYearShortName"].ToString();
var totalCustomer1 = a[0]["TotalCustomers"].ToString();
var totalCustomer2 = a[1]["TotalCustomers"].ToString();
var aquisition1 = a[0]["Aquisition"].ToString();
var aquisition2 = a[1]["Aquisition"].ToString();
var attrition1 = a[0]["Attrition"].ToString();
var attrition2 = a[1]["Attrition"].ToString();
JObject rss1 =
new JObject(
new JProperty("channel",
new JObject(
new JProperty("Key", "Attrition"),
new JProperty("color", "#d62728"),
new JProperty("values",
new JArray(
from p in a
select new JObject(
new JProperty("label", a[0]["MonthYearShortName"].ToString()),
new JProperty("value", attrition1),
new JProperty("label", a[1]["MonthYearShortName"].ToString()),
new JProperty("value", attrition2)))))));
When I tried this I get a
Can not add property label to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.
Now if someone can suggest a cleaner way (as I cant think of any right now), I would be greatful or if my code could be corrected, that would be helpful.
Thanks
Can you try doing it like this?
[Test]
public void Test()
{
var data = #"[
{'MonthYearShortName': 'Sep-13','TotalCustomers': 1905.0,'Aquisition': 317.0,'Attrition': 9.0},
{'MonthYearShortName': 'FY-14','TotalCustomers': 2158.0,'Aquisition': 401.0,'Attrition': 15.0909090909091}
]";
dynamic jarr = JArray.Parse(data);
var attritions = new List<ExpandoObject>();
var aquisitions = new List<ExpandoObject>();
var totalCustomers = new List<ExpandoObject>();
foreach (dynamic o in jarr)
{
dynamic attr = new ExpandoObject();
attr.label = o.MonthYearShortName;
attr.value = o.Attrition;
attritions.Add(attr);
dynamic acq = new ExpandoObject();
acq.label = o.MonthYearShortName;
acq.value = o.Aquisition;
aquisitions.Add(acq);
dynamic cust = new ExpandoObject();
cust.label = o.MonthYearShortName;
cust.value = o.TotalCustomers;
totalCustomers.Add(acq);
}
dynamic attrition = new ExpandoObject();
dynamic aquisition = new ExpandoObject();
dynamic totalCustomer = new ExpandoObject();
attrition.Key = "Attrition";
attrition.Color = "#d62728";
attrition.Values = attritions;
aquisition.Key = "Acquisition";
aquisition.Color = "#1f7774";
aquisition.Values = aquisitions;
totalCustomer.Key = "Total Customer";
totalCustomer.Color = "#1f77b4";
totalCustomer.Values = totalCustomers;
var result = new[] { attrition,totalCustomer, aquisition };
var resultString = JsonConvert.SerializeObject(result, Formatting.Indented);
Console.Write(resultString);
}
How do I deserialize this text. I tried with JSON but I get "Invalid JSON primitive" error.
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 1
},
"objects": [
{
"blocked": false,
"groups": [],
"id": "1111",
"name": "John Doe",
"number": "+15555555555",
"resource_uri": "/api/v1/contacts/1111/"
}
]
}
This is the code I used:
var jss = new JavaScriptSerializer();
var dictionary = jss.Deserialize<Dictionary<string, string>>(buffer.ToString());
Easy to Fix. Deserialize to <Dictionary<string, object> instead of <Dictionary<string, string>
var dictionary = jss.Deserialize<Dictionary<string, object>>(buffer.ToString());
Full test code
string json = #"{
""meta"": {
""limit"": 20,
""next"": null,
""offset"": 0,
""previous"": null,
""total_count"": 1
},
""objects"": [
{
""blocked"": false,
""groups"": [],
""id"": ""1111"",
""name"": ""John Doe"",
""number"": ""+15555555555"",
""resource_uri"": ""/api/v1/contacts/1111/""
}
]
}";
var jss = new JavaScriptSerializer();
var dictionary = jss.Deserialize<Dictionary<string, object>>(json);