how to add an object to a dictionary in c#? - c#

I need to create a JSON structure in the following format:
{
"test": [
{
"mode": "2",
"test": "test3"
},
{
"mode": "1",
"test": "test3"
}
]
}
So whenever a JSON structure is created, it should be appended to the test element.
So initially I will have only the value:
string json=#"{""testfun"": [ {""mode"": ""2"", ""test"": ""test3"" } ]}";
Dictionary<string, object> objtestnew2 = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
So how can I append when I get the next JSON structure to the existing dictionary element?

Split your creation of the dictionary, and the deserialization into two different steps.
The first time the method is called it should see if the dictionary exists, and if it doesn't create one. If it does exist, then you can append the deserialized data to that dictionary.

You can deserialize the second dictionary then just merge it into the first one. The simplest way to do it is a simple loop:
string json=#"{""testfun"": [ {""mode"": ""2"", ""test"": ""test3"" } ]}";
Dictionary<string, object> dict = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(json);
string json2=#"{""testfun"": [ {""mode"": ""1"", ""test"": ""test3"" } ]}";
Dictionary<string, object> dict2 = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(json2);
// loop through and update/add the items to the first dictionary
foreach(var item in dict2)
dict1[item.Key] = item.Value;

Related

Get key value pair from JSON string

I have a json string like
{
[
"EnrityList": "Attribute",
"KeyName": "AkeyName",
"Value": "Avalue"
],
[
"EnrityList": "BusinessKey",
"KeyName": "AkeyName",
"Value": "Avalue"
]
}
I have serialized and got an object array.
Could anyone help me to get the key value pair from these object array.
You can use JsonConvert from Newtonsoft.Json to deserialize json into Dictionary.
Dictionary<string, object> values =
JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonstring);
First convert the above string in proper json format by using :
str=str.Replace('[', '{');
str=str.Replace(']', '}');
//replace first occurance of {
int startPos = str.IndexOf('{');
str=str.Substring(0,startPos)+" ["+str.Substring(startPos + 1);
//replace last occurance of }
int endPos = str.LastIndexOf('}');
str=str.Substring(0,endPos)+"]";
This makes the string
str = [{"EnrityList":"Attribute","KeyName":"AkeyName","Value":"Avalue"}, {"EnrityList":"BusinessKey","KeyName":"AkeyName","Value":"Avalue"} ]
Now, since you got the json string, you can easily work with it.
we can use method as given by
How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?
foreach(KeyValuePair<string, string> entry in myDictionary)
{
// do something with entry.Value or entry.Key
}
Looking at your example, You are trying to receive a List of certain type of elements,
So First, You will need a class to represent your data type.
class MyType
{
string EnrityList;
string KeyName;
string Value;
}
Then use DesrializeObject method to store it in the variable
var values = JsonConvert.DeserializeObject<List<MyType>>(jsonstring);

Last entry in dictionary overwrites first written entry when adding dictionary to json file [duplicate]

This question already has an answer here:
Adding object to JArray overwriting first element
(1 answer)
Closed 4 years ago.
I have an existing json file which looks like this:
{
"players": [],
"games": []
}
I want to add objects to the players array so it looks like this:
{
"players": [
{
"name": "Peter",
"checksum": "6fa95b1427af77b3d769ae9cb853382f"
},
{
"name": "John",
"checksum": "61409aa1fd47d4a5332de23cbf59a36f"
},
{
"name": "Bob",
"checksum": "2fc1c0beb992cd7096975cfebf9d5c3b"
}
],
"games": []
}
Players are stored in a global Dictionary<string, string>. But in my implementation, the next element in the dictionary overwrites the first written element so when the loop is at John the next element would be Bob and then Peter gets replaced by Bob. The result of this looks like this:
{
"players": [
{
"name": "Bob",
"checksum": "2fc1c0beb992cd7096975cfebf9d5c3b"
},
{
"name": "John",
"checksum": "61409aa1fd47d4a5332de23cbf59a36f"
},
{
"name": "Bob",
"checksum": "2fc1c0beb992cd7096975cfebf9d5c3b"
}
],
"games": []
}
This is my code:
string json = File.ReadAllText("file.json");
JObject jsonObject = JObject.Parse(json);
JArray jsonPlayerArray = (JArray) jsonObject["players"];
JObject newPlayerEntry = new JObject();
var sortedDict = PlayerChecksumDict.OrderBy(x => x.Key);
foreach (var item in sortedDict)
{
newPlayerEntry["name"] = item.Key;
newPlayerEntry["checksum"] = item.Value;
jsonPlayerArray.Add(newPlayerEntry);
}
string modifiedJson = jsonObject.ToString(Formatting.Indented);
File.WriteAllText("file-modified.json", modifiedJson);
(Similar questions to this have been asked several times, but I haven't been able to find a duplicate, so I figure it's worth answering instead.)
You're creating a single JObject instance, then modifying it multiple times within your loop. Each iteration will overwrite the data set in the previous iteration. Your JArray ends up with lots of references to the same JObject.
Instead, you need to create a new JObject for each entry in your dictionary. To do this, you just need to move the declaration of newPlayerEntry into the loop:
var sortedDict = PlayerChecksumDict.OrderBy(x => x.Key);
foreach (var item in sortedDict)
{
JObject newPlayerEntry = new JObject();
newPlayerEntry["name"] = item.Key;
newPlayerEntry["checksum"] = item.Value;
jsonPlayerArray.Add(newPlayerEntry);
}
Now each element in the JArray will be a reference to a different JObject.

Json children properties to dictionary

I'm trying to extract a list of dates for a property of all children nodes on a JToken but cannot get the syntax correct.
I want to get a list of dates in property "timeStamp": "2013-09-11T00:30:00Z" so I can determine the min/max dates for all child nodes.
I've tried the following which returns an anonymous type and makes it difficult to use the returned object.
var timeStamps = Jarr.Select(x => new
{
timeStamp = (DateTime)x.SelectToken("timeStamp")
});
How can I get say a List<string> or List<DateTime> only of all child timestamps?
Is it possible to get a Dictionary<string, DateTime> of id, timestamp?
The Json looks like this, so essentially from LEVEL1 I want to check all children, children of children for the same property.
{
"children": [
{
"type": "LEVEL2",
"name": "Item1",
"id": "1.7193",
"timeStamp": "2013-09-11T00:30:00Z",
},
{
"type": "LEVEL2",
"name": "Item2",
"id": "1.7194",
"timeStamp": "2013-09-11T00:30:00Z",
},
{
"type": "LEVEL2",
"name": "Item3",
"id": "1.7191",
"timeStamp": "2013-09-11T00:30:00Z",
}
],
"type": "LEVEL1",
"name": "Stock-FRT54443",
"id": "1000145",
"countryCode": "en"
}
and method
void AddNodes(TreeView treeView, JObject jObj, TreeNodeCollection parent)
{
JToken Jarr = null;
Dictionary<string, string> marketProperties = new Dictionary<string, string>();
foreach (var property in jObj.Properties())
{
if (property.Name == "children")
{
Jarr = property.Value;
}
else
{
string key = property.Name;
string prop = property.Value.ToString();
marketProperties.Add(key, prop);
}
}
if (marketProperties["type"] == "LEVEL1")
{
//Not working!
var timeStamps = Jarr["timeStamp"].Values<string>();
}
}
When you use the 'new' keyword it's going to create an anonymous type. You're creating a list of objects with a timestamp property rather than a list of DateTimes. All you need to do to get your date list is to change it to:
DateTime timeStamps = Jarr.Select(x => (DateTime)x.SelectToken("timeStamp")).ToList();
It's also possible to get a dictionary:
Dict<string,DateTime> dictionary = Jarr["children"].ToDictionary(x=>x["Id"].ToString(),x=>(DateTime)(x["timeStamp"]));
The second is untested but should give you the general idea.

Deserialize a complex dynamic JSON string

What if the object to deserialize looked like this (where the keys Ioc, Name, id and timestamp are static, and the fields key is dynamic - meaning that it may contain a variable amount of items)???
{
"moduleinstances": [
{
"Ioc": "ioc1",
"Name": "name1",
"fields": {
"PV_PREFIX": "PIPE",
"TIMEOUT": "1"
},
"id": 25,
"timestamp": "/Date(1393518678000)/"
}
]
}
How to deserialize this kind of strings?
The secret is to keep your deserialized JSON in the most general form possible:
Dictionary<string, object> theData= new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(jsonString);
Dictionary<string, object> fieldsNode = (Dictionary<string, object>)theData["fields"];
string pv_prefix = (string)fieldsNode["PV_PREFIX"];
string timeout = (string)fieldsNode["TIMEOUT"];
The call to Deserialize() creates a tree of Dictionary<string, object> that you can traverse at will.

Parse Json without any property in c#

In my desktop application i want to parse a json file to Key,Value pair List .
Where Key is unique one and Value contains another list of Key,Value Pair . The striuctre of json string is
{
"mainkey1": {
"subkey10": [
value1
],
" subkey11":[
value2
]
},
"mainkey2": {
"subkey20": [
value0
],
"subkey21": [
value1
]
},
"mainkey3": {
"subkey30": [
value0
],
"subkey31": [
value1
]
}
.
.
.
.
.
}
How can i convert this kind of json string to some .Net object of key,value strings
key=string type value List
Any idea ?
Try deserializing to:
Dictionary<string, Dictionary<string,List<object>>>
...or use something like Newtonsoft's JSON library which has a JObject class representing any sort of JSON object .
Update:
To use the much-easier JavaScriptSerializer, just do this:
var serializer = new JavaScriptSerializer();
var obj = serializer.Deserialize<Dictionary<string, Dictionary<string, List<object>>>>(json);

Categories