जवाबों:
केवल संख्यात्मक या बूलियन मूल्यों वाले डेटा संरचनाओं को सीरियल करना काफी सरल है। यदि आपके पास क्रमबद्ध करने के लिए बहुत कुछ नहीं है, तो आप अपने विशिष्ट प्रकार के लिए एक विधि लिख सकते हैं।
एक के लिए Dictionary<int, List<int>>के रूप में आपके द्वारा निर्दिष्ट है, तो आप 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) + "}";
}
लेकिन, यदि आप कई अलग-अलग वर्गों, या अधिक जटिल डेटा संरचनाओं को क्रमबद्ध कर रहे हैं, या विशेष रूप से यदि आपके डेटा में स्ट्रिंग मान हैं , तो आप एक प्रतिष्ठित JSON लाइब्रेरी का उपयोग करना बेहतर होगा जो पहले से ही जानता है कि भागने के पात्रों और लाइन ब्रेक जैसी चीजों को कैसे संभालना है। Json.NET एक लोकप्रिय विकल्प है।
इस उत्तर में Json.NET का उल्लेख किया गया है, लेकिन आपको यह बताने से रोक दिया जाता है कि आप किसी शब्दकोश को क्रमबद्ध करने के लिए Json.NET का उपयोग कैसे कर सकते हैं:
return JsonConvert.SerializeObject( myDictionary );
JavaScriptSerializer के विपरीत, काम करने के लिए JsonConvert myDictionaryके प्रकार का शब्दकोश होना आवश्यक नहीं है <string, string>।
Json.NET शायद अब C # शब्दकोशों को पर्याप्त रूप से अनुक्रमित करता है , लेकिन जब ओपी ने मूल रूप से इस प्रश्न को पोस्ट किया, तो कई MVC डेवलपर्स जावास्क्रिप्ट से वर्ग का उपयोग कर रहे होंगे, क्योंकि यह बॉक्स से बाहर डिफ़ॉल्ट विकल्प था।
यदि आप एक विरासत परियोजना (MVC 1 या MVC 2) पर काम कर रहे हैं, और आप Json.NET का उपयोग नहीं कर सकते हैं, तो मेरा सुझाव है कि आप List<KeyValuePair<K,V>>इसके बजाय का उपयोग करें Dictionary<K,V>>। लीगेसी JavaScriptSerializer वर्ग इस प्रकार को ठीक प्रकार से क्रमबद्ध करेगा, लेकिन इसमें शब्दकोश की समस्या होगी।
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()));
}
}
}
}
यह कंसोल को लिखेगा:
[{\"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]}]
( using System.Web.Script.Serialization)
यह कोड किसी Dictionary<Key,Value>को भी रूपांतरित करेगा Dictionary<string,string>और फिर इसे JSON स्ट्रिंग के रूप में अनुक्रमित करेगा:
var json = new JavaScriptSerializer().Serialize(yourDictionary.ToDictionary(item => item.Key.ToString(), item => item.Value.ToString()));
यह ध्यान देने योग्य है कि Dictionary<int, MyClass>जटिल प्रकार / वस्तु को संरक्षित करते हुए कुछ इस तरह से भी धारावाहिक किया जा सकता है।
var yourDictionary = new Dictionary<Key,Value>(); //This is just to represent your current Dictionary.
आप चर yourDictionaryको अपने वास्तविक चर से बदल सकते हैं ।
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.
हम ऐसा करते हैं, क्योंकि की और वैल्यू दोनों को टाइप स्ट्रिंग का होना आवश्यक है, क्योंकि सीरीज़ की आवश्यकता होती है 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.
System.Web.Extensionsक्लाइंट फ्रेमवर्क संस्करण में नहीं है, लेकिन पूर्ण संस्करण की भी आवश्यकता है।
क्षमा करें यदि वाक्यविन्यास सबसे छोटा बिट है, लेकिन मुझे जो कोड मिल रहा है वह मूल रूप से 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);
Asp.net कोर उपयोग में:
using Newtonsoft.Json
var obj = new { MyValue = 1 };
var json = JsonConvert.SerializeObject(obj);
var obj2 = JsonConvert.DeserializeObject(json);
System.Coreऔर फिर संदर्भ देने की कोशिश की using Newtonsoft.Jsonऔर कोई खुशी नहीं हुई। मुझे लगता Newtonsoftहै कि एक 3-पार्टी पुस्तकालय है।
यहाँ Microsoft से केवल मानक .Net पुस्तकालयों का उपयोग करने का तरीका बताया गया है ...
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());
}
Dictionary<string, dynamic>सभी JSON आदिम प्रकारों जैसे इंटरजर्स, फ्लोट्स, बुलियन, स्ट्रिंग्स, यहां तक कि नल और एक वस्तु के भीतर जोड़ सकते हैं । +1
आप जावास्क्रिप्ट सर्वर का उपयोग कर सकते हैं ।
string। मैंने यहां एक उत्तर पोस्ट किया है जिसमें शामिल है, यदि आप एक नज़र रखना चाहते हैं।
यह विभिन्न पुस्तकालयों का एक बहुत लगता है और पिछले वर्षों में आने और जाने के लिए क्या नहीं लगता है। हालांकि अप्रैल 2016 तक, इस समाधान ने मेरे लिए अच्छा काम किया। स्ट्रेट्स को आसानी से स्ट्रेट्स द्वारा प्रतिस्थापित किया जाता है ।
//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();
}
दो आयात बिंदु। सबसे पहले, Visual Studio's Solution Explorer के अंदर अपने प्रोजेक्ट में एक संदर्भ के रूप में System.Runtime.Serliazation जोड़ना सुनिश्चित करें। दूसरा, इस लाइन को जोड़ें,
using System.Runtime.Serialization.Json;
फ़ाइल के शीर्ष पर अपने शेष usings के साथ, इसलिए DataContractJsonSerializerकक्षा पाई जा सकती है। यह ब्लॉग पोस्ट में क्रमांकन के इस तरीके के बारे में अधिक जानकारी है।
मेरा डेटा 3 स्ट्रिंग्स के साथ एक शब्दकोश है, प्रत्येक स्ट्रिंग्स की एक सूची की ओर इशारा करता है। तार की सूचियों की लंबाई 3, 4, और 1. डेटा इस प्रकार है:
StringKeyofDictionary1 => ["abc","def","ghi"]
StringKeyofDictionary2 => ["String01","String02","String03","String04"]
Stringkey3 => ["someString"]
फ़ाइल में लिखा गया आउटपुट एक लाइन पर होगा, यहाँ प्रारूपित आउटपुट है:
[{
"Key": "StringKeyofDictionary1",
"Value": ["abc",
"def",
"ghi"]
},
{
"Key": "StringKeyofDictionary2",
"Value": ["String01",
"String02",
"String03",
"String04",
]
},
{
"Key": "Stringkey3",
"Value": ["SomeString"]
}]
यह वही है जो मेरिट ने पहले पोस्ट किया था। बस पूरा कोड पोस्ट करना
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;
}
यदि आपका संदर्भ इसे (तकनीकी बाधाओं, आदि) की अनुमति देता है, तो न्यूटनसॉफ्टJsonConvert.SerializeObject से विधि का उपयोग करें । संदेश : यह आपके जीवन को आसान बना देगा।
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"}