How to access children values of a JObject - c#

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

Related

deserialize nested json data 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"];

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:

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.

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

accessing items in an json.net jarray in c#

My API returns
{
"result": [
{
"id": "51473",
"name": "serv-vc",
"modifydate": "2014-10-09 18:29:48.033",
"expirationoff": "false",
"createdate": "",
"scheduleoff": "false",
}
],
"status": 0
}
which I've stored as a JObject reponseobj
I'm having trouble figuring out how to access responseobj["result"][0]["id"].
Every time I try that, it gives an array about being out of bounds.
What am I missing?
I also tried
JArray resultarr = (JArray)responseobj.SelectToken("result");
resultarr[0]["id"]
but have the same results.
Assuming the response is in a string variable called response, this would do it:
JObject responseobj = JObject.Parse(response);
JObject result = (JObject)(responseobj.SelectToken("result") as JArray).First();
int id = result.Value<int>("id");
Try using:
JObject jObject = JObject.Parse( "{\"result\": [{\"id\": \"51473\", \"name\": \"serv-vc\", \"modifydate\": \"2014-10-09 18:29:48.033\", \"expirationoff\": \"false\", \"createdate\": \"\", \"scheduleoff\": \"false\", } ], \"status\": 0 }" );
And to access to the different nodes, you can use:
string name = jObject["result"]["name"].ToString();
string expirationoff = jObject["result"]["expirationoff"].ToString();
Or you can convert result in a new json a work on it
And to access to result you can do:
var result = jObject["result"][0];
Remember that you can have 0, 1, 2... x numbers of results in your json, then you need do reference to the first position.
Not sure what's your issue, but this seems to work for me :
static void Main(string[] args)
{
JObject j = JObject.Parse(
"{\"result\": [{\"id\": \"51473\", \"name\": \"serv-vc\", \"modifydate\": \"2014-10-09 18:29:48.033\", \"expirationoff\": \"false\", \"createdate\": \"\", \"scheduleoff\": \"false\", } ], \"status\": 0 }" );
var res = j["result"];
Console.Out.WriteLine(res);
// show an arrays
var maybe = j["result"][0];
Console.Out.WriteLine(maybe);
// shows the first object in the array
var fail = j["result"][0]["id"];
Console.Out.WriteLine(fail);
// shows 51473
}
var Jobj = ((JObject)RequestObject)["data"];
foreach (JObject content in Jobj.Children<JObject>()) {
foreach (JProperty prop in content.Properties()) {
Console.WriteLine(prop.Name);//the column name
Console.WriteLine(prop.Value.ToString());// column value
}
}

Categories