How to create JSON from C# dictionary similar to PHP - c#

PHP code to make an array
$tag = array(
'tag_uid' => 1234,
'x' => 0,
'y' => 0
);
$tags[] = $tag;
OUTPUT: {"x":"0","y":"0","tag_uid":"1234"}
I want to make this as JSON array in C# with the same OUTPUT for that I need help, I can't figure out which array it will be? a simple array or what.
I have tag_uid which i can pass to function and i am using JSON.NET I don't know what should i need to write in the JsonArry function but I have tried to following
public JsonArray CreatePhotoTag(string userId)
{
Dictionary<string, object> tagParameters = new Dictionary<string, object>();
tagParameters.Add("x", "0");
tagParameters.Add("y", "0");
tagParameters.Add("tag_uid", userId);
JsonArray tagsarray = ???
return tagsarray ;
}
Please help me

I recommend switching to ServiceStack.NET Text. It is incredibly fast compared to JSON.NET.
You can serialize it like this:
ServiceStack.NET
var jsonSerializer = new JsonSerializer<Dictionary<String, Object>>();
var tagsArray = jsonSerializer.SerializeToString(tagParameters);
If you really want to use JSON.NET
JSON.NET
var tagsArray = JsonConvert.SerializeObject(tagParameters, Formatting.Indented);

Related

How to convert json key value array to DTO in C# [duplicate]

I'm quite new to JSON, and am currently learning about (de)serialization.
I'm retrieving a JSON string from a webpage and trying to deserialize it into an object. Problem is, the root json key is static, but the underlying keys are dynamic and I cannot anticipate them to deserialize. Here is a mini example of the string :
{
"daily": {
"1337990400000": 443447,
"1338076800000": 444693,
"1338163200000": 452282,
"1338249600000": 462189,
"1338336000000": 466626
}
}
For another JSON string in my application, I was using a JavascriptSerializer and anticipating the keys using class structure. What's the best way to go about deserializing this string into an object?
Seriously, no need to go down the dynamic route; use
var deser = new JavaScriptSerializer()
.Deserialize<Dictionary<string, Dictionary<string, int>>>(val);
var justDaily = deser["daily"];
to get a dictionary, and then you can e.g.
foreach (string key in justDaily.Keys)
Console.WriteLine(key + ": " + justDaily[key]);
to get the keys present and the corresponding values.
You can use dynamic in .NET 4 or later. For example with JSON.NET I can do:
dynamic obj = JsonConvert.Deserialize<dynamic>("{x: 'hello'}");
You can then do:
var str = obj.x;
However, unsure how it will handle numeric keys. You can of course just use JObject directly itself, for example:
var obj = JObject.Parse("{'123456': 'help'}");
var str = obj["123456"];
Whenever you have JSON with dynamic keys it can usually be deserialized into a Dictionary<string, SomeObject>. Since the inner JSON keys are dynamic (in this question) the JSON can be modelled as:
Dictionary<string, Dictionary<string, int>>
I would recommend using NewtonSoft.Json (JSON.Net) or System.Text.Json (if you're working in .NET-Core 3.0 and up).
Newtonsoft.Json
Use DeserializeObject<T> from JsonConvert:
var response = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, int>>>(json);
System.Text.Json
Use Deserialize<T> from JsonSerializer:
var response = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, int>>>(json);
This is not convenient to use, because in с# can not be defined a variable starts with a number. Add prefix to keys.
Or try this:
string json = "
{ daily:[
{ key: '1337990400000', val:443447 },
{ key: '1338076800000', val:444693 },
{ key: '1338163200000', val:452282 },
{ key: '1338249600000', val:462189 },
{ key: '1338336000000', val:466626 }]
}";
public class itemClass
{
public string key; // or int
public int val;
}
public class items
{
public itemClass[] daily;
}
items daily = (new JavascriptSerializer()).Deserialize<items>(json);
Then you can:
var itemValue = items.Where(x=>x.key=='1338163200000').Select(x=>x.val).FirstOrDefault();

How to create array of key/value pair in c#?

I have an application that is written on top of ASP.NET MVC. In one of my controllers, I need to create an object in C# so when it is converted to JSON using JsonConvert.SerializeObject() the results looks like this
[
{'one': 'Un'},
{'two': 'Deux'},
{'three': 'Trois'}
]
I tried to use Dictionary<string, string> like this
var opts = new Dictionary<string, string>();
opts.Add("one", "Un");
opts.Add("two", "Deux");
opts.Add("three", "Trois");
var json = JsonConvert.SerializeObject(opts);
However, the above creates the following json
{
'one': 'Un',
'two': 'Deux',
'three': 'Trois'
}
How can I create the object in a way so that JsonConvert.SerializeObject() generate the desired output?
Your outer JSON container is an array, so you need to return some sort of non-dictionary collection such as a List<Dictionary<string, string>> for your root object, like so:
var opts = new Dictionary<string, string>();
opts.Add("one", "Un");
opts.Add("two", "Deux");
opts.Add("three", "Trois");
var list = opts.Select(p => new Dictionary<string, string>() { {p.Key, p.Value }});
Sample fiddle.

JSON array to C# Dictionary

How do I convert a JSON array like this
[{"myKey":"myValue"},
{"anotherKey":"anotherValue"}]
to a C# Dictionary with json.net or system classes.
json.net can serialize directly to a dictionary, but only if you feed it an object, not an array.
Maybe converting to array of KeyValuePairs will help
using System.Linq;
var list = JsonConvert.DeserializeObject<IEnumerable<KeyValuePair<string, string>>>(jsonContent);
var dictionary = list.ToDictionary(x => x.Key, x => x.Value);
For anyone interested - this works, too:
Example JSON:
[{"device_id":"VC2","command":6,"command_args":"test args10"},
{"device_id":"VC2","command":3,"command_args":"test args9"}]
C#:
JsonConvert.DeserializeObject<List<JObject>>(json)
.Select(x => x?.ToObject<Dictionary<string, string>>())
.ToList()
Its quite simple actually :
lets say you get your json in a string like :
string jsonString = #"[{"myKey":"myValue"},
{"anotherKey":"anotherValue"}]";
then you can deserialize it using JSON.NET as follows:
JArray a = JArray.Parse(jsonString);
// dictionary hold the key-value pairs now
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = (string)p.Value;
dict.Add(name,value);
}
}
I found that using a list of KeyValuePairs didn't work. I got the right number of elements but they had null Keys and Values.
In the end the only solution that worked for me was deserialising to a list of dictionaries (which each had a single kvp element).
The data must to be sent as follows (format):
"Values": [
{"Key" : "abc" , "Value": 23.14},
{"Key" : "abc1" , "Value": 23.11},
{"Key" : "abc2" , "Value": 23.17},
{"Key" : "abc3" , "Value": 23.19}
]
thereby, the converting process will work. It worked fine to me in my attempt to convert from JSON to dictionary<string,decimal>
Since you can only deserialize from an object, do just that by manipulating the JSON string a little first. Wrap it in an object:
json = String.Format("{{\"result\":{0}}}", json);

How to deserialize currencies list from openexchangerates.org to C# custom class or object?

I need to get currency values list in C# from here:
http://openexchangerates.org/currencies.json
which produces this kind of output:
{
"AED": "United Arab Emirates Dirham",
"AFN": "Afghan Afghani",
"ALL": "Albanian Lek",
"AMD": "Armenian Dram",
"ANG": "Netherlands Antillean Guilder",
"AOA": "Angolan Kwanza"
// and so on
}
I managed to get a string containing values above using C#, but I cannot find a way to deserialize that string into any custom class or anonymous object, so I am wondering how to do that?
Also, I am trying to use Json.NET to do that, but so far couldn't find a solution...
using Json.Net
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonString);
--EDIT--
You can make it shorter
WebClient w = new WebClient();
string url = "http://openexchangerates.org/currencies.json";
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(w.DownloadString(url));
A solution using only .Net 4.0 and no third party libraries:
string url = "http://openexchangerates.org/currencies.json";
var client = new System.Net.WebClient();
string curStr = client.DownloadString(url);
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
var res = (js.DeserializeObject(curStr) as Dictionary<string, object>)
.Select(x => new { CurKey = x.Key, Currency = x.Value.ToString() });
Outputs a list of anonymous objects with the keys and values from the list as properties.
Enjoy :)

fastJSON ToJSON into dictionary?

How to use fastJSON (or some other JSON lib, possibly) to dump some data into a dictionary format, e.g. {"key1": "valstring", "key2": 1234}?
If I try to dump Dictionary<string, Object> I get something like [{"k":"key1","v":"valstring"},{"k":"key2","v":1234}] instead.
We use Json.NET at our office. We send json objects between python and C#. We ran into the same problem, though ours was just the differences in how the languages naturally serialized it.
The best part about it, if I'm remember correctly, is that it had this behavior right out of the box.
var dict = new Dictionary<string, string>();
dict.Add("key", "val");
dict.Add("key2", "val2");
string json = JsonConvert.SerializeObject(dict);
Json should equal { "key": "val", "key2": "val2" }
You just can use JavaScriptSerializer to create your solution, it's native for .Net.
var dict = new Dictionary<string, string>();
dict.Add("key", "val");
dict.Add("key2", "val2");
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(dict);
And you'l get result you are expected: {"key1": "valstring", "key2": 1234}
(fastJSON) You need use some parameters parameters:
_jsonParameters = new JSONParameters
{
EnableAnonymousTypes = true,
SerializeToLowerCaseNames = true,
UseFastGuid = false,
KVStyleStringDictionary = false <---- THIS
};
}
JSON.ToJSON(obj, _jsonParameters)

Categories