C#에서 사전을 JSON 문자열로 변환하려면 어떻게 해야 하나요?
변환하고 싶다Dictionary<int,List<int>>JSON 문자열로 이동합니다.C#에서 이 작업을 수행하는 방법을 아는 사람이 있습니까?
이 답변은 Json을 언급하고 있습니다.NET은 Json의 사용 방법에 대해서는 설명하지 않습니다.사전을 직렬화하려면 NET:
return JsonConvert.SerializeObject( myDictionary );
JavaScriptSerializer와 달리myDictionary형식 사전일 필요는 없습니다.<string, string>JsonConvert가 작동하도록 합니다.
숫자 값 또는 부울 값만 포함하는 데이터 구조를 직렬화하는 것은 매우 간단합니다.연재할 것이 별로 없는 경우는, 특정의 타입의 메서드를 작성할 수 있습니다.
의 경우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은 현재 C# 사전을 적절히 시리얼화하지만 OP가 이 질문을 처음 게시했을 때 많은 MVC 개발자가 JavaScriptSerializer 클래스를 사용하고 있었을 가능성이 있습니다.이는 기본 옵션이었기 때문입니다.
레거시 프로젝트(MVC 1 또는 MVC 2)에서 작업 중 Json을 사용할 수 없는 경우.NET의 경우,List<KeyValuePair<K,V>>대신Dictionary<K,V>>. 레거시 JavaScriptSerializer 클래스는 이 유형을 정상적으로 시리얼화하지만 사전에는 문제가 있습니다.
문서:Json을 사용하여 컬렉션을 직렬화합니다.네트워크
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.
구문이 조금이라도 어긋났다면 죄송합니다만, 이것을 취득한 코드는 원래 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);
사용의 컨텍스트에서 허가되고 있는 경우(기술상의 제약 등),JsonConvert.SerializeObject뉴턴소프트의 메서드.Json: 그것은 너의 삶을 더 편하게 해줄 거야.
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"}
Asp.net의 핵심 용도:
using Newtonsoft.Json
var obj = new { MyValue = 1 };
var json = JsonConvert.SerializeObject(obj);
var obj2 = JsonConvert.DeserializeObject(json);
하시면 됩니다.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 : 시스템.텍스트, Json.Json Serializer 입니다.시리얼라이즈(dict)
JavaScriptSerializer를 사용할 수 있습니다.
그것은 많은 다른 도서관들과 지난 몇 년 동안 오고 가지 않았던 것 같다.하지만 2016년 4월 현재 이 솔루션은 나에게 잘 작동했습니다.문자열은 ints로 쉽게 대체됩니다.
TL/DR: 목적이라면 복사해 주세요.
//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();
}
Import 포인트 2개먼저 시스템을 추가해야 합니다.런타임Visual Studio의 솔루션 탐색기 내 프로젝트에서 참조할 수 있는 Serlization.둘째, 이 행을 추가합니다.
using System.Runtime.Serialization.Json;
맨, "사용법"은 "사용법"에 달라집니다.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"]
}]
다음은 표준만을 사용하여 수행하는 방법입니다.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());
}
이것은 Meritt가 이전에 게시한 것과 유사합니다.완전한 코드를 게시하는 것 뿐입니다.
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;
}
솔루션 : UWP는 하고 있습니다.Windows.Data.Json.
JsonObject할 수 입니다.
var options = new JsonObject();
options["foo"] = JsonValue.CreateStringValue("bar");
string json = options.ToString();
향상된 mwjohnson 버전:
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;
}
언급URL : https://stackoverflow.com/questions/5597349/how-do-i-convert-a-dictionary-to-a-json-string-in-c
'programing' 카테고리의 다른 글
| mongodb로부터의 transparent_hugepage/defrag 경고를 회피하려면 어떻게 해야 합니까? (0) | 2023.03.01 |
|---|---|
| ng-show 및 ng-animate를 사용한 슬라이드 업/다운 효과 (0) | 2023.03.01 |
| '읽기 전용' 유형에 '값' 속성이 없습니다.< { } > (0) | 2023.03.01 |
| 색인 페이지의 WordPress wp_title 공백 (0) | 2023.03.01 |
| 스프링 3 주석을 사용하여 심플한 공장 패턴 구현 (0) | 2023.03.01 |