Extracting variable data from JSON in C# - c#

I have the following JSON which I need to manipulate into a different JSON format to be consumed by another process. My data is variable to some extent. Here is an example:
{
"subform_12": {
"multiline_2": "Subform 1 Long Text",
"listpicker_5": "High",
"alpha_1": "SubForm 1 Text"
},
"subform_13": {
"multiline_2": "Subform 2 Long Text",
"alpha_1": "SubForm 2 Text"
}
}
The variable part is the name of the json object (eg "subform_13") and the number and content of name pairs per object (eg "multiline_2": "Subform 1 Long Text").
What I need to do is convert each node into its own chunk of json, as in the following format:
{
"subform_13": [
[{
"fieldKey": "multiline_2",
"value": "Subform 2 Long Text"
},
{
"fieldKey": "alpha_1",
"value": "SubForm 2 Text"
}
]
]
}
Then separately:
{
"subform_13": [
[{
"fieldKey": "multiline_2",
"value": "Subform 2 Long Text"
},
{
"fieldKey": "alpha_1",
"value": "SubForm 2 Text"
}
]
]
}
So far I see that I can iterate thru the list as follows:
var json = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(
jsonString,
new Newtonsoft.Json.JsonSerializerSettings()
{
DateParseHandling = Newtonsoft.Json.DateParseHandling.None,
});
foreach (var item in json)
{
// I can see the "subform_13" and contents here in item , how do I generically extract them?
}
Any help appreciated.

Here is your Main method augmented with the ability to iterate through all values:
static void Main(string[] args)
{
var json = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string,JObject>>(
jsonString,
new Newtonsoft.Json.JsonSerializerSettings()
{
DateParseHandling = Newtonsoft.Json.DateParseHandling.None,
});
foreach (var item in json)
{
var key = item.Key; // "subform_12"
var val = item.Value;
Console.WriteLine(key+":");
foreach (var field in val)
{
var fieldKey = field.Key; // e.g. "multiline_2"
var fieldVal = field.Value; // e.g. "Subform 1 Long Text"
Console.WriteLine($"{fieldKey}={fieldVal.Value<string>()}");
}
Console.WriteLine();
}
}
I am just printing the values out; you would construct your new objects - for example as dynamic - using these values.
The output of my Main is:
subform_12:
multiline_2=Subform 1 Long Text
listpicker_5=High
alpha_1=SubForm 1 Text
subform_13:
multiline_2=Subform 2 Long Text
alpha_1=SubForm 2 Text
Hope it helps.

There are probably more elegant ways using linq, but here's code using a plain old JavaScriptSerializer from System.Web.Extensions.
There is a result dictionary, which you probably don't need if you want each object separated.
The json strings for each object is stored in the allJson list.
Similary, if you want the dictionary objects themselves you could just add seperated to a list during each iteration.
string s = "{\"subform_12\":{\"multiline_2\":\"Subform 1 Long Text\",\"listpicker_5\":\"High\",\"alpha_1\":\"SubForm 1 Text\"},\"subform_13\":{\"multiline_2\":\"Subform 2 Long Text\",\"alpha_1\":\"SubForm 2 Text\"}}";
JavaScriptSerializer ser = new JavaScriptSerializer();
Dictionary<string, object> obj = ser.DeserializeObject(s) as Dictionary<string, object>;
// combined dictionary of all results
Dictionary<string, object> result = new Dictionary<string, object>();
// an intermediary dictionary to house the results of each object
Dictionary<string, object> separated = new Dictionary<string, object>();
// a list to hold the json representation of each separate object
List<String> allJson = new List<string>();
foreach (KeyValuePair<string, object> src in obj)
{
Dictionary<string, object> children = (Dictionary<string, object>)src.Value;
Dictionary<string, object> t = new Dictionary<string, object>();
separated = new Dictionary<string, object>();
List<object> l = new List<object>();
foreach (KeyValuePair<string, object> child in children)
{
t.Add("fieldKey", child.Key);
t.Add("value", child.Value);
l.Add(t);
t = new Dictionary<string, object>();
}
separated.Add(src.Key, l.ToArray());
allJson.Add(ser.Serialize(separated));
result.Add(src.Key, l.ToArray());
}
// final string containing all transformed objects combined.
string combined = ser.Serialize(result);

Related

Serialize flat Dictionary into multi-sub-object JSON

In C# I have a flat Dictionary<string, string> where keys are in form of obj1/obj2/obj3 and values are direct string. Now I want to serialize that into subobjects, so example values:
var dict = new Dictionary<string, string> { {"foo/bar/baz1", "123" }, {"foo/baz", "456" }, { "foo/abc", "def" } };
should result with:
{
"foo": {
"bar": {
"baz1": "123"
},
"baz": "456",
"abc": "def"
}
}
Optionally I want to remove quotes around "123" and "456" in output if they can be interpreted as numbers or booleans.
I am using Newtonsoft.JSON
You can parse a source dictionary into JObject using JObject.FromObject method. Then go through all of properties, split them using string.Split and parse recursively to a new JObject, representing a properties tree. Finally add this object to the destination one using JObject.Add, or update it if the given key is already exist
var dict = new Dictionary<string, string> { { "foo/bar/baz1", "123" }, { "foo/baz", "456" }, { "foo/abc", "def" } };
var source = JObject.FromObject(dict);
var dest = new JObject();
foreach (var property in source.Properties())
{
//split the name into parts
var items = property.Name.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
var item = items.FirstOrDefault();
if (string.IsNullOrEmpty(item))
continue;
//get JObject representing a properties tree
var result = WriteItems(items.Skip(1).ToList(), property.Value);
//check that destination already contains top property name (e.g. 'foo')
if (dest.ContainsKey(item))
{
(dest[item] as JObject)?.Add(result.First);
}
else
{
dest.Add(item, result);
}
}
Console.WriteLine(dest.ToString());
//local function to recursively go through all properties and create a result JObject
JObject WriteItems(IList<string> items, JToken value)
{
var item = items.FirstOrDefault();
items.RemoveAt(0);
if (!items.Any()) //no more items in keys, add the value
return new JObject(new JProperty(item, value));
return new JObject(new JProperty(item, WriteItems(items, value)));
}
It produces the following output
{
"foo": {
"bar": {
"baz1": "123"
},
"baz": "456",
"abc": "def"
}
}
Also, the code above allows you to handle a properties tree with any depth. I don't think that there is a built-in way to serialize the structure like foo/bar/baz1 into sub-objects in Json.NET

C# Deserialize string of multiple arrays with json-string in it explicit to List<string>

i have a json-string, or bit more something like a "string of arrays":
"[
{
"type":"radio-group",
"label":"Radio-Button-Gruppe",
"name":"radio-group-1556028993486",
"className":"iCheck",
"values":[
{
"label":"aaaaaaa",
"value":"aaaaaaa"
},
{
"label":"bbbbbbbbb",
"value":"bbbbbbbbb"
},
{
"label":"cccccccccccc",
"value":"cccccccccccc"
}
]
}
],
[
...
],
[
{
"type":"header",
"label":"Überschrift"
}
]"
Now I want to have a List<string> of each array in this string. Something like:
List<string> x[0] = "{
"type":"radio-group",
"label":"Radio-Button-Gruppe",
"name":"radio-group-1556028993486",
"className":"iCheck",
"values":[
{
"label":"aaaaaaa",
"value":"aaaaaaa"
},
{
"label":"bbbbbbbbb",
"value":"bbbbbbbbb"
},
{
"label":"cccccccccccc",
"value":"cccccccccccc"
}
]
}"
What's the best way to do that?
I already tried out JsonConvert.DeserializeObject<IEnumerable<string>>() but my problem is that he wants to deserialize my jsons to an object. But I want to keep them as a string und put them to my list.
Why I need a list of string for each array?
Because I use the json-strings inside the arrays to render a form. each array show you a page of the form, and the json is the data for rendering this form.
to render this form i have to go through a loop through all of this arrays and render the json in it for every page.
You can use JsonConvert.DeserializeObject<IEnumerable<JToken>>(json) where json is each of your top level arrays. Then you can iterate through the results and use .ToString() on each JToken object.
As others have pointed out, you don't have valid JSON, so I didn't try to give a solution to parse out the top level arrays.
var json = #"[
{
""type"":""radio-group"",
""label"":""Radio-Button-Gruppe"",
""name"":""radio-group-1556028993486"",
""className"":""iCheck"",
""values"":[
{
""label"":""aaaaaaa"",
""value"":""aaaaaaa""
},
{
""label"":""bbbbbbbbb"",
""value"":""bbbbbbbbb""
},
{
""label"":""cccccccccccc"",
""value"":""cccccccccccc""
}
]
}
]";
var arrays = new[] { json };
var objectsAsStrings = new List<string>();
foreach (var array in arrays)
{
var tokens = JsonConvert.DeserializeObject<IEnumerable<JToken>>(array);
foreach (var token in tokens)
{
objectsAsStrings.Add(token.ToString());
}
}
var json = "yourjson";
var jsonnew = "[" + json+ "]";
var list = JsonConvert.DeserializeObject<dynamic>(jsonnew);
var result = new List<string>();
foreach (var item in list)
{
var str = JsonConvert.SerializeObject(item);
result.Add(str);
}
You can use this , too.

Dictionary Manipulations in C#

I want to store the following values into a dictionary:
key (string) - values (list of strings)
aaa - myfirstvalue1
aaa - myfirstvalue2
bbb - myfirstvalue3
ccc - myfirstvalue4
ccc - myfirstvalue5
Dictionary:
Dictionary<string, List<string> myvalues = new Dictionary<string, List<string>>();
I tried to store these values but I got the duplicate key error.
Dictionaries have the feature that a key can be added only once. You have the right type, but the way you add the data matters.
You can initialize the dictionary with the data provided like this:
Dictionary<string, List<string>> myvalues = Dictionary<string, List<string>>
{
{ "aaa", new List<string> { "myfirstvalue1", "myfirstvalue2" } },
{ "bbb", new List<string> { "myfirstvalue3" } },
{ "ccc", new List<string> { "myfirstvalue4", "myfirstvalue5" } },
};
With this, each key has one list of strings assigned to it. You can add more values like this:
var key = "aaa"; // for example
if (myvalues.ContainsKey(key)
{
myvalues[key].Add("new value");
}
else
{
myvalues.Add(key, new List<string> { "new value" });
}
You can retrieve values like this:
List<string> aaaVals = myvalues["aaa"];
and then convert that List<string> to an Array with List.ToArray().

Parsing JSON with fastJson in C#

I could not find an answer in the existing threads for my problem. I have this JSON string:
{
"Count": 4,
"Result:000": {
"Score": 4.571,
"W0DateTime": "2014-08-28 23:00:00",
"W0Value": 1.0164,
"W0Fibonacci": 0,
"Direction": "SHORT",
"StartDate": "2014-08-29 16:30:00",
"EndDate": "2014-08-28 01:00:00",
"BarsCalculated": 80
}
}
How do I get the content of Result:000?
I have this code:
...
public Dictionary<string, object> dictionaryObject;
public void jsonInitStructure(string sJsonString)
{
dictionaryObject = (Dictionary<string , object>) fastJSON.JSON.Parse(sJsonString);
}
...
Count is easy: Convert.ToInt32(dictionaryObject ["Count"]) but how do I get the values from Result:000? For example (Score, StartDate, EndDate, ...)
Have you tried casting it?
var result000 = (Dictionary<string, object>)dictionaryObject["Result:000"];
var result000Score = Convert.ToDouble(result000["Score"]);
Plese have a try...
Array objList = (Array)dictionaryObject["Result:000"] ;
foreach (object obj in objList)
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary = (Dictionary<string, object>)obj;
var var1 = dictionary["Score"].ToString();
var var2 = dictionary["W0DateTime"].ToString();
}

Get values and keys in json object using Json.Net C#

Hi there I have json that looks like this:
{
"Id": " 357342524563456678",
"title": "Person",
"language": "eng",
"questionAnswer": [
{
"4534538254745646.1": {
"firstName": "Janet",
"questionNumber": "1.1"
}
}
]
}
Now I have written some code that loops over the objects in the questionAnswer array and then gets the name of the object which is 4534538254745646.1. Now Im trying to save the key of each Item and the value aswell but I am only managing to get the value.
How would I do this, here is my code:
JToken entireJson = JToken.Parse(json);
JArray inner = entireJson["questionAnswer"].Value<JArray>();
foreach(var item in inner)
{
JProperty questionAnswerDetails = item.First.Value<JProperty>();
//This line gets the name, which is fine
var questionAnswerSchemaReference = questionAnswerDetails.Name;
var properties = questionAnswerDetails.Value.First;
//This only gets Janet
var key = properties.First;
var value = properties.Last;
}
So at the moment Im only able to get Janet, But I also want the firstname field. I want to then take this and add to a dictionary i.e.
Dictionary<string, string> details = new Dictionary<string, string>();
//suedo
foreach(var item in questionAnswerObjects)
details.Add(firstName, Janet);
//And then any other things found below this
So Here is he complete code that gets the keys and values for each item in the object in the array:
string key = null;
string value = null;
foreach(var item in inner)
{
JProperty questionAnswerDetails = item.First.Value<JProperty>();
var questionAnswerSchemaReference = questionAnswerDetails.Name;
var propertyList = (JObject)item[questionAnswerSchemaReference];
questionDetails = new Dictionary<string, object>();
foreach (var property in propertyList)
{
key = property.Key;
value = property.Value.ToString();
}
questionDetails.Add(key, value);
}
I can now add key and value to the dictionary

Categories

Resources