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();
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();
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 :)
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);
I want to convert my Dictionary<int,List<int>> to JSON string. Does anyone know how to achieve this in C#?
This answer mentions Json.NET but stops short of telling you how you can use Json.NET to serialize a dictionary:
return JsonConvert.SerializeObject( myDictionary );
As opposed to JavaScriptSerializer, myDictionary does not have to be a dictionary of type <string, string> for JsonConvert to work.
Serializing data structures containing only numeric or boolean values is fairly straightforward. If you don't have much to serialize, you can write a method for your specific type.
For a Dictionary<int, List<int>> as you have specified, you can use Linq:
string MyDictionaryToJson(Dictionary<int, List<int>> dict)
{
var entries = dict.Select(d =>
string.Format("\"{0}\": [{1}]", d.Key, string.Join(",", d.Value)));
return "{" + string.Join(",", entries) + "}";
}
But, if you are serializing several different classes, or more complex data structures, or especially if your data contains string values, you would be better off using a reputable JSON library that already knows how to handle things like escape characters and line breaks. Json.NET is a popular option.
Json.NET probably serializes C# dictionaries adequately now, but when the OP originally posted this question, many MVC developers may have been using the JavaScriptSerializer class because that was the default option out of the box.
If you're working on a legacy project (MVC 1 or MVC 2), and you can't use Json.NET, I recommend that you use a List<KeyValuePair<K,V>> instead of a Dictionary<K,V>>. The legacy JavaScriptSerializer class will serialize this type just fine, but it will have problems with a dictionary.
Documentation: Serializing Collections with Json.NET
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Dictionary<int, List<int>> foo = new Dictionary<int, List<int>>();
foo.Add(1, new List<int>( new int[] { 1, 2, 3, 4 }));
foo.Add(2, new List<int>(new int[] { 2, 3, 4, 1 }));
foo.Add(3, new List<int>(new int[] { 3, 4, 1, 2 }));
foo.Add(4, new List<int>(new int[] { 4, 1, 2, 3 }));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<int, List<int>>));
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, foo);
Console.WriteLine(Encoding.Default.GetString(ms.ToArray()));
}
}
}
}
This will write to the console:
[{\"Key\":1,\"Value\":[1,2,3,4]},{\"Key\":2,\"Value\":[2,3,4,1]},{\"Key\":3,\"Value\":[3,4,1,2]},{\"Key\":4,\"Value\":[4,1,2,3]}]
Simple One-Line Answer
(using System.Web.Script.Serialization )
This code will convert any Dictionary<Key,Value> to Dictionary<string,string> and then serialize it as a JSON string:
var json = new JavaScriptSerializer().Serialize(yourDictionary.ToDictionary(item => item.Key.ToString(), item => item.Value.ToString()));
It is worthwhile to note that something like Dictionary<int, MyClass> can also be serialized in this way while preserving the complex type/object.
Explanation (breakdown)
var yourDictionary = new Dictionary<Key,Value>(); //This is just to represent your current Dictionary.
You can replace the variable yourDictionary with your actual variable.
var convertedDictionary = yourDictionary.ToDictionary(item => item.Key.ToString(), item => item.Value.ToString()); //This converts your dictionary to have the Key and Value of type string.
We do this, because both the Key and Value has to be of type string, as a requirement for serialization of a Dictionary.
var json = new JavaScriptSerializer().Serialize(convertedDictionary); //You can then serialize the Dictionary, as both the Key and Value is of type string, which is required for serialization.
Sorry if the syntax is the tiniest bit off, but the code I'm getting this from was originally in VB :)
using System.Web.Script.Serialization;
...
Dictionary<int,List<int>> MyObj = new Dictionary<int,List<int>>();
//Populate it here...
string myJsonString = (new JavaScriptSerializer()).Serialize(MyObj);
If your context allows it (technical constraints, etc.), use the JsonConvert.SerializeObject method from Newtonsoft.Json : it will make your life easier.
Dictionary<string, string> localizedWelcomeLabels = new Dictionary<string, string>();
localizedWelcomeLabels.Add("en", "Welcome");
localizedWelcomeLabels.Add("fr", "Bienvenue");
localizedWelcomeLabels.Add("de", "Willkommen");
Console.WriteLine(JsonConvert.SerializeObject(localizedWelcomeLabels));
// Outputs : {"en":"Welcome","fr":"Bienvenue","de":"Willkommen"}
In Asp.net Core use:
using Newtonsoft.Json
var obj = new { MyValue = 1 };
var json = JsonConvert.SerializeObject(obj);
var obj2 = JsonConvert.DeserializeObject(json);
You can use System.Web.Script.Serialization.JavaScriptSerializer:
Dictionary<string, object> dictss = new Dictionary<string, object>(){
{"User", "Mr.Joshua"},
{"Pass", "4324"},
};
string jsonString = (new JavaScriptSerializer()).Serialize((object)dictss);
net core :
System.Text.Json.JsonSerializer.Serialize(dict)
You could use JavaScriptSerializer.
It seems a lot of different libraries and what not have seem to come and go over the previous years. However as of April 2016, this solution worked well for me. Strings easily replaced by ints.
TL/DR; Copy this if that's what you came here for:
//outputfilename will be something like: "C:/MyFolder/MyFile.txt"
void WriteDictionaryAsJson(Dictionary<string, List<string>> myDict, string outputfilename)
{
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Dictionary<string, List<string>>));
MemoryStream ms = new MemoryStream();
js.WriteObject(ms, myDict); //Does the serialization.
StreamWriter streamwriter = new StreamWriter(outputfilename);
streamwriter.AutoFlush = true; // Without this, I've run into issues with the stream being "full"...this solves that problem.
ms.Position = 0; //ms contains our data in json format, so let's start from the beginning
StreamReader sr = new StreamReader(ms); //Read all of our memory
streamwriter.WriteLine(sr.ReadToEnd()); // and write it out.
ms.Close(); //Shutdown everything since we're done.
streamwriter.Close();
sr.Close();
}
Two import points. First, be sure to add System.Runtime.Serliazation as a reference in your project inside Visual Studio's Solution Explorer. Second, add this line,
using System.Runtime.Serialization.Json;
at the top of the file with the rest of your usings, so the DataContractJsonSerializer class can be found. This blog post has more information on this method of serialization.
Data Format (Input / Output)
My data is a dictionary with 3 strings, each pointing to a list of strings. The lists of strings have lengths 3, 4, and 1.
The data looks like this:
StringKeyofDictionary1 => ["abc","def","ghi"]
StringKeyofDictionary2 => ["String01","String02","String03","String04"]
Stringkey3 => ["someString"]
The output written to file will be on one line, here is the formatted output:
[{
"Key": "StringKeyofDictionary1",
"Value": ["abc",
"def",
"ghi"]
},
{
"Key": "StringKeyofDictionary2",
"Value": ["String01",
"String02",
"String03",
"String04",
]
},
{
"Key": "Stringkey3",
"Value": ["SomeString"]
}]
Here's how to do it using only standard .Net libraries from Microsoft …
using System.IO;
using System.Runtime.Serialization.Json;
private static string DataToJson<T>(T data)
{
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer serialiser = new DataContractJsonSerializer(
data.GetType(),
new DataContractJsonSerializerSettings()
{
UseSimpleDictionaryFormat = true
});
serialiser.WriteObject(stream, data);
return Encoding.UTF8.GetString(stream.ToArray());
}
This is Similar to what Meritt has posted earlier. just posting the complete code
string sJSON;
Dictionary<string, string> aa1 = new Dictionary<string, string>();
aa1.Add("one", "1"); aa1.Add("two", "2"); aa1.Add("three", "3");
Console.Write("JSON form of Person object: ");
sJSON = WriteFromObject(aa1);
Console.WriteLine(sJSON);
Dictionary<string, string> aaret = new Dictionary<string, string>();
aaret = ReadToObject<Dictionary<string, string>>(sJSON);
public static string WriteFromObject(object obj)
{
byte[] json;
//Create a stream to serialize the object to.
using (MemoryStream ms = new MemoryStream())
{
// Serializer the object to the stream.
DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
ser.WriteObject(ms, obj);
json = ms.ToArray();
ms.Close();
}
return Encoding.UTF8.GetString(json, 0, json.Length);
}
// Deserialize a JSON stream to object.
public static T ReadToObject<T>(string json) where T : class, new()
{
T deserializedObject = new T();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedObject.GetType());
deserializedObject = ser.ReadObject(ms) as T;
ms.Close();
}
return deserializedObject;
}
Just for reference, among all the older solutions: UWP has its own built-in JSON library, Windows.Data.Json.
JsonObject is a map that you can use directly to store your data:
var options = new JsonObject();
options["foo"] = JsonValue.CreateStringValue("bar");
string json = options.ToString();
improved mwjohnson's version:
string WriteDictionaryAsJson_v2(Dictionary<string, List<string>> myDict)
{
string str_json = "";
DataContractJsonSerializerSettings setting =
new DataContractJsonSerializerSettings()
{
UseSimpleDictionaryFormat = true
};
DataContractJsonSerializer js =
new DataContractJsonSerializer(typeof(Dictionary<string, List<string>>), setting);
using (MemoryStream ms = new MemoryStream())
{
// Serializer the object to the stream.
js.WriteObject(ms, myDict);
str_json = Encoding.Default.GetString(ms.ToArray());
}
return str_json;
}