deserialize nested json data c# - c#

I am using javascriptserializer to deserialize json data. I am stuck on how to parse this data and assign the value to a variable.
json:
{
"data1": {
"EntityList": "Attribute",
"KeyName": "AkeyName",
"Value": "Avalue"
},
"data2": {
"Id": "jsdksjkjdiejkwp12193jdmsldm",
"Status": "OK"
}
}
I need to assign the values of EntityList, KeyName in data1 to a variable. I read this json string into a variable data
c#:
var data = "json string"; //variable with json string
JavaScriptSerializer jss = new JavaScriptSerializer();
dynamic drecord = jss.Deserialize<dynamic>(data);
I am trying to parse this nested json into 2 variables EntityList & KeyName.

If I understood you correct so it must be smth like this:
JavaScriptSerializer jss = new JavaScriptSerializer();
dynamic record = jss.Deserialize<dynamic>(data);
var data1 = record["data1"];
var entityList = data1["EntityList"];
var keyName = data1["KeyName"];

Related

JObject in C# for independent data fetching of JSON

I am using Json.Net to parse my JSON
This is my JSON:
"OptionType": {
"C": [
"C",
"Call"
],
"P": [
"P",
"Put"
]
}
Before this step, when processed, as a result, I would get a value from any of this.
For example Option Type: Call
Whatever value I get, I need it to be transcodified according to the above JSON.
Example: Option Type: C
First of all your sample data is not a valid JSON. You need to wrap it to the curvy braces.
If your sample is a part of the JSON object, you can map OptionType to the Dictionary<string, List<string>>.
To find valid option you will need to iterate this dictionary like in the sample below:
var valueToCheck = "Call";
string type = null;
foreach (var kvp in optionTypes)
{
if (kvp.Value.Contains(valueToCheck))
{
type = kvp.Key;
break;
}
}
Same using JObject with fixed JSON data:
var json = #"{
""OptionType"":{
""C"": [
""C"",
""Call""
],
""P"": [
""P"",
""Put""
]
}
}";
var valueToCheck = "Call";
string type = null;
var ot = JObject.Parse(json);
var objectType = ot["OptionType"];
foreach (var token in objectType)
{
var prop = token.ToObject<JProperty>();
var key = prop.Name;
var values = prop.Value.ToObject<List<string>>();
if (values.Contains(valueToCheck))
{
type = key;
break;
}
}
Code is not perfect but it is just an idea what to do.
You need to iterate over properties of JObject and then search your option type and then replace your search option with its parent key.
This is custom function can do above task.
public static JObject GetJObject(JObject jObject, List<string> optionType)
{
foreach (var type in jObject["OptionType"])
{
var key = type.ToObject<JProperty>().Name;
var values = type.ToObject<JProperty>().Value.ToObject<List<string>>();
foreach (var option in optionType)
{
if (values.Contains(option))
{
int index = values.IndexOf(option);
values.RemoveAt(index);
values.Insert(index, key);
}
}
JToken jToken = JToken.FromObject(values);
jObject.SelectToken("OptionType." + key).Replace(jToken);
}
return jObject;
}
And you can use above custom function this like
string json = File.ReadAllText(#"Path to your json file");
JObject jObject = JObject.Parse(json);
List<string> optionType = new List<string> { "Call", "Put" };
JObject result = GetJObject(jObject, optionType);
Output:

How to access children values of a JObject

I have a JObject item that looks like this:
{
"part":
{
"values": ["engine","body","door"]
"isDelivered": "true"
},
{
"manufacturer":
{
"values": ["Mercedes"]
"isDelivered": "false"
}
}
How can I get the values as a single string in C#?
First create JObject from your string
String json = "{\"part\":{ \"values\": [\"engine\",\"body\",\"door\"], \"isDelivered\": \"true\"},\"manufacturer\":{\"values\": [\"Mercedes\"],\"isDelivered\": \"false\"}}";
JObject jObject = JObject.Parse(json);
Then get values array (from part for example as)
JArray jArray= (JArray)jObject["part"]["values"];
Convert JArray of String to string array
string[] valuesArray = jArray.ToObject<string[]>();
Join your string array & create a singe string
String values = string.Join(",",valuesArray);
Full code here ..
String json = "{\"part\":{ \"values\": [\"engine\",\"body\",\"door\"], \"isDelivered\": \"true\"},\"manufacturer\":{\"values\": [\"Mercedes\"],\"isDelivered\": \"false\"}}";
JObject jObject = JObject.Parse(json);
JArray jArray= (JArray)jObject["part"]["values"];
string[] valuesArray = jArray.ToObject<string[]>();
String values = string.Join(",",valuesArray);
Console.WriteLine(values);
First things first, that json is not properly formatted, it should be:
{
"part":
{
"values": ["engine","body","door"],
"isDelivered": "true"
},
"manufacturer":
{
"values": ["Mercedes"],
"isDelivered": "false"
}
}
Now, getting to the answer, I believe this is what you want
var jObject = JObject.Parse(testJson);
var children = jObject.Children().Children();
var valuesList = new List<string>();
foreach (var child in children)
{
valuesList.AddRange(child["values"].ToObject<List<string>>());
}
var valuesJsonArray = JsonConvert.SerializeObject(valuesList); // not sure if you want an array of strings or a json array of strings

JSON Serialize array returns NULL in JSON string

I am building a JSON model like this
JObject issue_model = JObject.FromObject(new
{
labels = new[] { "import", "automation"}
}
below code for serialization
string request_json = JsonConvert.SerializeObject(issue_model,
Newtonsoft.Json.Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
But when i try to build this from a dynamic list of values like
list<string> lp_list = new list<string>();
//lp_list contains a list of string values
string[] lp_labels = lp_list.ToArray();
JObject issue_model = JObject.FromObject(new
{
labels = jira_labels
}
I got the JSON as
"labels": [
[
null,
null
]
]
But i am expecting this json as
"labels" : { "import", "automation"}
How can i make the array serialization right way
I modified your code in a console Application.
List<string> lp_list = new List<string>();
lp_list.Add("import");
lp_list.Add("automation");
//lp_list contains a list of string values
//string[] lp_labels = lp_list.ToArray();
JObject issue_model = JObject.FromObject(new
{
labels = lp_list
});
Console.WriteLine(issue_model);
The result is as follows:
Hope it answers your question.

C# items as root nodes of JSON

I'm trying to pass a Json that I'd like to access from jquery as,
jdata.comType
my c# code is,
var frontChartList = new List<object>();
frontChartList.Add(new
{
comType = comType,
today = DateTime.Now.ToString("D"),
agentsAdded = "53",
agentsAvail = "47",
packageAvailDays = leftDays.ToString(),
});
JavaScriptSerializer jss = new JavaScriptSerializer();
String json = jss.Serialize(frontChartList);
return json;
I cannot access this as
jdata.comType
only as,
jdata[0].comType
how should I create the JSON to get a string accessible as jdata.comType?
since I will only be passing one object in this.
Because your frontChartList is a List<object>, change it to single object instead:
var frontChartList = new
{
comType = comType,
today = DateTime.Now.ToString("D"),
agentsAdded = "53",
agentsAvail = "47",
packageAvailDays = leftDays.ToString(),
});

Write a JObject from a JArray using the object's Key-Pair values in C#

I have a JArray which looks as follows:
[
{
"key": "S8710 Server",
"value": "M"
},
{
"key": "Java",
"value": "M"
}
]
This JArray needs to be converted into a JObject by taking the key and value such that the output object looks like this:
{
"S8710 Server": "M",
"Java": "M"
}
Is this conversion Possible? Any help would be greatly appreciated.
What I tried is extracting the keys and values from a DataTable and serializing the result of that. Then I tried JObject.Parse.
var skillList = from skill in ds.Tables[4].AsEnumerable()
where skill.Field<Int64>("ResumeID") == applicantValue.ResumeID
select new clsResume.ExtractRatingInfo
{
key = skill.Field<string>("Skill"),
value = skill.Field<string>("SkillRating")
};
string skillResult = JsonConvert.SerializeObject(skillList, Newtonsoft.Json.Formatting.None);
JObject obj = JObject.Parse(skillResult);
Yes, you can transform your JSON like this:
JObject result = new JObject(
jArray.Select(jt => new JProperty((string)jt["key"], jt["value"]))
);
Fiddle: https://dotnetfiddle.net/CcLj3D
Note: the keys must be distinct across all objects in the array for this to work properly.
Create JToken by passing the content string into JArray`s static method Parse.
get the inner childs from JToken and then look for the properties and their values.
like this:
JArray jArray = JArray.Parse(YOUR_CONTENT_GOES_HERE);
foreach (var token in jArray.Children<JToken>())
{
var firstProp = token.Children<JProperty>().First(param => param.Name == "S8710 Server");
var firstValue = firstProp.Value<string>();
var secondProp = token.Children<JProperty>().First(param => param.Name == "Java");
var secondValue = firstProp.Value<string>();
}

Categories