Working with a string in JSON format - c#

I have a long string in JSON format. This is what it looks like:
{"ShowMapUrl":true,"GameDiffusionType":5,"InputYellowCards":false,"DisplayYellowCards":false,"InputYellowCards2":false}
Note that the string is much longer. I've been trying to convert that string into a dictionary by using json.NET without success. Any tips?

Use JsonConvert.DeserializeObject<Dictionary<string, object>>():
var json = #"{""ShowMapUrl"":true,""GameDiffusionType"":5,""InputYellowCards"":false,""DisplayYellowCards"":false,""InputYellowCards2"":false}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

Related

How can I get the values of some part of a json string?

I'm working with this Json structure, but I don't know how to get the values of the part of the "json" key
I'm using this code to send a request to an API, and the return is an Json object:
var reqData = (HttpWebRequest)WebRequest.Create(string.Format("http://server_ip/system/message/date/{0}/", txtDate.Text));
reqData.ContentType = "application/json";
reqData.Method = "GET";
var answer = (HttpWebResponse)reqData.GetResponse();
List<Dictionary<string, string>> convert = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(answer);
The result is a Json structure like this:
"[
{
\"idMessage\":\"--Message Id--",
\"idTemplate\":--TemplateId--,
\"mail\":\"--mail dir--\",
\"subject\":\"--message subject--\",
\"json\":\"{
\\\"Id\\\":\\\"--Person Id--\\\",
\\\"name\\\":\\\"--Person name--\\\",
\\\"date\\":\\\"--Register date-\\\",
\\\"hour\\\":\\\"--Register hour--\\\"
}\",
\"senddate\":\"--sent date--\",
\"status\":0,
\"template\":null
}
]"
I want to get the values (Id,name,date,hour) from the json part of this Json string, can someone help me to get this values?
That json property contains a string of more JSON, so you have to deserialize that again, the same way you did the whole outer structure.
So now that you have your convert array, you can pull out the first object, grab the value of json and deserialize that:
var json = JsonConvert.DeserializeObject<Dictionary<string, string>>(convert[0]["json"]);
Then you can pull each value out like this:
var id = json["Id"];
Mind you, the JSON in your question isn't actually valid. There are a few errors in it. But I'm assuming that they're just copy/paste errors and the web service is actually returning valid JSON.

C# Json deserialize - property as variable

I have problem. From json: https://api.csgofast.com/price/all I would like to get property name as variable. Can I do it with Newtonsoft Json library? Thanks in advance for help.
You can deserialize this JSON into a Dictionary<string, decimal> like this:
var prices = JsonConvert.DeserializeObject<Dictionary<string, decimal>>(json);

De-serialize JSON array in c#

I have a very odd JSON array as follows
[["1","hello"],["2","hello2"],["3","hello3"],["",""],["",""],[null,null],[null,null],[null,null],[null,null],[null,null]]
I need to de-serialize in c# but there doesn't seem to be anything common to convert it to I tried string but then I get the follow error:
Type string is not supported for deserialization of an array.
This is the code I tried:
string jsonString = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<string>(json);
How would you get at the strings in the JSON?
You could deserialize it to an array of string arrays:
string[][] jsonString = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<string[][]>(json);
Or maybe a list of string-tuples (Dictionary could be problematic due to the lack of unique keys):
List<Tuple<string, string>> jsonString = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialze<List<Tuple<string, string>>(json);

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.

How to deserialize JSON to Dictionary using JSON.NET?

I am querying data from http://www.imdbapi.com and would like to parse the result using Json.net library. Could someone please tell me how I can use this library to convert the query response into a Map<string, string>.
With this code I'm able to get all keys, but how can query the values then?
JObject obj = JObject.Parse(response);
IList<string> props = obj.Properties().Select(p => p.Name).ToList();
Try JSON.NET
Just use this:
Dictionary<string, string> movieValues =
JsonConvert.DeserializeObject<Dictionary<string, string>>(responseFromImdbApi);
Just get the values like this:
movieValues["title"]
movieValues["released"]
movieValues["genre"]
Why would you use an external library when it is already available ?
JavaScriptSerializer works great.

Categories