C #에서 사전을 JSON 문자열로 어떻게 변환합니까?
내 Dictionary<int,List<int>>
JSON 문자열 로 변환하고 싶습니다 . C #에서 이것을 달성하는 방법을 아는 사람이 있습니까?
숫자 또는 부울 값만 포함하는 데이터 구조 를 직렬화 하는 것은 매우 간단합니다. 직렬화 할 것이 많지 않은 경우 특정 유형에 대한 메소드를 작성할 수 있습니다.
A의 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 # 사전을 적절하게 직렬화 할 것입니다. 그러나 OP 가이 질문을 처음 게시했을 때 많은 MVC 개발자가 JavaScriptSerializer 클래스를 사용하고 있었을 것입니다.
레거시 프로젝트 (MVC 1 또는 MVC 2)에서 작업 중이고 Json.NET을 사용할 수없는 경우 List<KeyValuePair<K,V>>
대신을 사용하는 것이 좋습니다 Dictionary<K,V>>
. 레거시 JavaScriptSerializer 클래스는이 유형을 올바르게 직렬화하지만 사전에 문제가 있습니다.
문서 : 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()));
}
}
}
}
콘솔에 쓸 것입니다 :
[{\"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
)
이 코드는 any 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.
우리는 키와 값이 모두 문자열 유형이어야하기 때문에 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.
구문이 가장 작은 비트 인 경우 미안하지만이 코드를 원래 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);
당신은 사용할 수 있습니다 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);
Asp.net Core에서 :
using Newtonsoft.Json
var obj = new { MyValue = 1 };
var json = JsonConvert.SerializeObject(obj);
var obj2 = JsonConvert.DeserializeObject(json);
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"]
}]
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;
}
참고URL : https://stackoverflow.com/questions/5597349/how-do-i-convert-a-dictionary-to-a-json-string-in-c
'Programming' 카테고리의 다른 글
Android : 가로 모드 용 대체 레이아웃 XML (0) | 2020.07.16 |
---|---|
ImageButton에 텍스트를 표시하는 방법? (0) | 2020.07.16 |
vim에서 창을 뒤집는 방법? (0) | 2020.07.16 |
Objective-C : 카테고리의 특성 / 인스턴스 변수 (0) | 2020.07.16 |
입력 초점에서 텍스트 선택 (0) | 2020.07.16 |