Convert Dictionary to JSON in C# - c#

first time asking questions here.
I currently have a Dictionary in C# that I want to serialize into JSON using:
Dictionary<string, List<string> myDict = new Dictionary<string, List<string>();
string json = JsonConvert.SerializeObject(myDict);
Works A1, getting results
{"Key1":["Item1","Item2","Item3"],"Key2":["Item1","Item2","Item3"]}
However, I would like to get my JSON response in this format to be usable with Jquery addons:
{"ID":"Key1", "Value": ["Val":"Item1","Val:":"Item2","Val":"Item3"]
}, { "ID":"Key2",
"Value":["Val":"Item1","Val:":"Item2","Val":"Item3"] }
Without having to loop through the dictionary and rebuild it manually. Is there any decent ways to do it?
Thank you

Related

Getting Collection text while serializing List<string> inside a Dictionary using JsonConvert in C# [duplicate]

This question already has answers here:
How can I serialize/deserialize a dictionary with custom keys using Json.Net?
(4 answers)
Closed 6 months ago.
So I have the following data structure defined in my program:
Dictionary<string, Dictionary<List<string>, int>> myTopDict = new Dictionary<string, Dictionary<List<string>, int>>();
Dictionary<List<string>, int> myInnerDict = new Dictionary<List<string>, int>();
int myIntValue=1;
List<string> myListValue=new List<string>();
myListValue.Add("Example Text 1");
myListValue.Add("Example Text 2");
//Here I add to my inner dictionary
myInnerDict.Add(myListValue, myIntValue);
//And finally adding to top dictionary
myTopDict.Add("My Data Set", myInnerDict);
//Serialize here
string result = JsonConvert.SerializeObject(myTopDict);
When I serialize the data structure, I am getting Collection text in the string as shown below:
What am I doing wrong here? Why I am not able to see my data in the serialized result?
For me the main problem that you have in your code is that you are using inside the dictionary as a key a list of string. That's why it's appering like that when you serialize the json
I don't know the expected Json result that you want. But if the idea is to have a collection of values, so change the Dictionary<string, Dictionary<List, int>> to Dictionary<string, Dictionary<string, List>>
Then the serialization will work different
Again, I really don't know the expected output or if that code is what you really want.

Output a JSON property name with a dash using an anonymous object

I am using a third party API which is like this below. It uses Json serializer to output
public Output(string name, object value);
I have to place the following json string in my output file from C#
Output("somename", new {my-name : "somevalue"})
The issue is C# does not allow identifiers with dash (-). How do I achieve this ?
Tried putting raw value like below but it adds back slash (\) to the file output which is not going very well.
Output("somename", #"{""my-name"":""somevalue""}")
Any thoughts ?
Since you are using an anonymous object, the simplest workaround would be to create a Dictionary<string, string> instead:
Output("somename", new Dictionary<string, string> { { "my-name", "somevalue" } });
Serialization of a dictionary as a JSON object in which the dictionary keys are mapped to JSON property names is supported by many .Net JSON serializers including json.net and javascriptserializer and even datacontractjsonserializer when UseSimpleDictionaryFormat = true as noted here.
And if you have values of different types and are using a serializer that supports arbitrary polymorphism during serialization (Json.NET and JavaScriptSerializer do) you could use a Dictionary<string, object>:
Output("somename",
new Dictionary<string, object>
{
{ "my-name", "somevalue" },
{ "my-id", 101 },
{ "my-value", value },
});

Correctly iterating through json array

I am trying to parse through an json array and get the values from it but facing some issues.
I have my json that I get as:
[{
"ID1":"1",
"ID2":"2",
"ID3":"3",
"ID4":"4"
},
{
"ID1":"5",
"ID2":"6",
"ID3":"7",
"ID4":"8"
}]
The key ID1, ID2 etc are not fixed. For ex I can also have my json as:
[{
"ID1":"1",
"ID2":"2"
},
{
"ID1":"5",
"ID2":"6"
}]
Or there can be more keys also, ie its dynamic so I cant create a model and map my json to it.
I was trying to deserialize that and get the data by using the following code.:
public IActionResult GetData(string data)
{
//here data is my json
List<string> myList = JsonConvert.DeserializeObject<List<string>>(data);
foreach (string s in myList)
{
//get values here
}
return Json("");
}
But above gives me error when deserializing as:
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while >parsing value: {. Path '', line 1, position 2.'
So I wanted to know how what is the correct method to loop through this json and get key values from it.
Your JSON is a list of object, your issue is that you are trying to deserialize into a list of string. This will not work for obvious reasons.
Instead you want to deserialize into a list of objects, and since your objects keys change the best thing you can use is a Dictionary<string, string>:
var myList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(data);
Keep in mind that the JSON you posted is a Dictionary<string, string> but as soon as you get integers or bools in that JSON you should change to Dictionary<string, object>
Fiddle here

Dynamically serialise JSON with the ability to omit entries

I am using an API that frustratingly requires you to omit optional parameters rather than pass them as null.
Also, data is slightly nested in the format:
{ data: { prop1: 5, prop2: 6, prop3: 7 } }
Previously I was converting it using a replace:
"{ data: { prop1: {prop1}, prop2: {prop2}, prop3: {prop3} } }"
.Replace("{prop1}", prop1)....
But it turns out that if a value is not provided the API I am sending this to will only accept it if it's not included in the JSON.
Rather than mess around with complex string concatenation (as I am not using model binding), I thought about simply creating a dictionary and serialising it to JSON.
If I do this:
Dictionary<string, int> props = new Dictionary<string, int>
{
{ "prop1", 6 },
{ "prop3", 7 },
};
string json = JsonConvert.SerializeObject(props, Formatting.Indented);
I can serialise whichever props I need nicely. Unfortunately you can see the way I need to send the data is contained within the data property of the json. I would need to put a dictionary inside my dictionary, but the dictionary is defined as string, int so that isn't possible. If I changed the type, then I'd not be able to put my props in.
To solve this I can see 2 possible clean ways:
Dynamically compose a JSON object somehow sorta like XML
eg. new JsonObject().AddNode("data").AddProperty("Prop1", 3).AddProperty("Prop3", 5).... etc.
Serialise from a dictionary object in a way that will let me include the nested property. Or, find a way to assign the json from a non-nested dictionary into the data property of a new json object.
I've not found a way to do this cleanly yet - alternatively another suggestion on solving this issue would be appreciated.
Not sure what your problem is with the dictionary approach. This works fine:
var props = new Dictionary<string, Dictionary<string, int>>
{
{ "data", new Dictionary<string, int>
{
{"prop1", 6},
{"prop3", 7}
}
}
};
var json = JsonConvert.SerializeObject(props, Formatting.Indented);

how to serialize a json string to a form post data

I need to POST a JSON string to a page.
The page is external and out of my control, and it expects the post data to be in the web-form post format (key1=value1&key2=value2)
How can I convert the JSON string to this format?
This can be done by first deserializing your JSON to a Dictionary<string, string>, then iterating through the key-value pairs in the dictionary and building up a querystring from that.
However, keep in mind that querystring format (application/x-www-form-urlencoded) is not a hierarchical format, while JSON is. So your JSON object can only be a simple object with key-value pairs (no arrays or nested objects). If your JSON is more complicated than that, you will have to do some more work to flatten it before you can convert it to a querystring.
Demo:
class Program
{
static void Main(string[] args)
{
string json = #"
{
""key1"" : ""value1"",
""key2"" : ""value2"",
""int"" : 5,
""bool"" : true,
""decimal"" : 3.14,
""punct"" : ""x+y=z""
}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> kvp in dict)
{
if (!string.IsNullOrEmpty(kvp.Key) && !string.IsNullOrEmpty(kvp.Value))
{
if (sb.Length > 0) sb.Append('&');
sb.Append(HttpUtility.UrlEncode(kvp.Key));
sb.Append('=');
sb.Append(HttpUtility.UrlEncode(kvp.Value));
}
}
var postDataString = sb.ToString();
Console.WriteLine(postDataString);
}
}
Output:
key1=value1&key2=value2&int=5&bool=True&decimal=3.14&punct=x%2by%3dz
As was mentioned in the comments, you can use the FormUrlEncodedContent class to do the same thing. Replace the StringBuilder and foreach loop in the code above with the following (but note this approach requires async/await):
var formUrlEncodedContent = new FormUrlEncodedContent(dict);
var postDataString = await formUrlEncodedContent.ReadAsStringAsync();
You don't post JSON like that. You set the Content-Type header to "application/json" and then you simply fill the content body with the JSON as-is.
There is no built in support in C# or JSON.NET to serialize JSON into form post data, but you can probably use LINQ to JSON to write a translater yourself relatively easy, assuming the JSON format is simple enough.
Is the Json being passed in always the same? Your best bet is to deserialize the Json to a C# class then create your post data from that.

Categories