다음 코드가 있습니다:
var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent);
응답 내용`의 입력은 JSON이지만 객체로 제대로 구문 분석되지 않습니다. 어떻게 역직렬화해야 하나요?
Json.NET]1(Newtonsoft.Json NuGet 패키지)를 사용하고 있지 않다고 가정합니다. 이 경우 시도해 보시기 바랍니다.
다음과 같은 기능이 있습니다:
아래 예제를 보세요. 이 예제에서 JsonConvert
클래스는 객체를 JSON으로 변환하는 데 사용됩니다. 이를 위해 두 개의 정적 메서드가 있습니다. 두 메서드는 SerializeObject(Object obj)
과 DeserializeObject<T>(String json)
입니다:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
여기에 답변됨 것과 - 데즈리얼리즈 C # 에 JSON 동적 객체?
dynamic stuff = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
string name = stuff.Name;
string address = stuff.Address.City;
사용하거나 뉴턴소프t.j손드링크:
dynamic stuff = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
string name = stuff.Name;
string address = stuff.Address.City;
// For that you will need to add reference to System.Runtime.Serialization
var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }"), new System.Xml.XmlDictionaryReaderQuotas());
// For that you will need to add reference to System.Xml and System.Xml.Linq
var root = XElement.Load(jsonReader);
Console.WriteLine(root.XPathSelectElement("//Name").Value);
Console.WriteLine(root.XPathSelectElement("//Address/State").Value);
// For that you will need to add reference to System.Web.Helpers
dynamic json = System.Web.Helpers.Json.Decode(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }");
Console.WriteLine(json.Name);
Console.WriteLine(json.Address.State);
[시스템.웹스헬퍼s.j슨] [1] 에 대한 자세한 내용은 링크를 참조.
// minimum supported version: Win 8
JsonObject root = Windows.Data.Json.JsonValue.Parse(jsonString).GetObject();
Console.WriteLine(root["Name"].GetString());
Console.WriteLine(root["Address"].GetObject()["State"].GetString());
[1]: http://msdn.microsoft.com/en-us/library/system.web.helpers.json% 111%29.aspx 28v = vs.
.NET 4를 사용할 수 있는 경우 확인하세요: http://visitmix.com/writings/the-rise-of-json (archive.org)
다음은 해당 사이트의 스니펫입니다:
WebClient webClient = new WebClient();
dynamic result = JsonValue.Parse(webClient.DownloadString("https://api.foursquare.com/v2/users/self?oauth_token=XXXXXXX"));
Console.WriteLine(result.response.user.firstName);
마지막 Console.WriteLine은 꽤 멋지네요...
using System.Web.Script.Serialization;
.
JavaScriptSerializer serializer = new JavaScriptSerializer();
objectString = serializer.Serialize(new MyObject());
뒤로를
MyObject o = serializer.Deserialize<MyObject>(objectString)
이제 시스템.j슨 작동됨.
설치처 누제 https://www.nuget.org/packages/System.Json
PM> Install-Package System.Json -Version 4.5.0
// PM>Install-Package System.Json -Version 4.5.0
using System;
using System.Json;
namespace NetCoreTestConsoleApp
{
class Program
{
static void Main(string[] args)
{
// Note that JSON keys are case sensitive, a is not same as A.
// JSON Sample
string jsonString = "{\"a\": 1,\"b\": \"string value\",\"c\":[{\"Value\": 1}, {\"Value\": 2,\"SubObject\":[{\"SubValue\":3}]}]}";
// You can use the following line in a beautifier/JSON formatted for better view
// {"a": 1,"b": "string value","c":[{"Value": 1}, {"Value": 2,"SubObject":[{"SubValue":3}]}]}
/* Formatted jsonString for viewing purposes:
{
"a":1,
"b":"string value",
"c":[
{
"Value":1
},
{
"Value":2,
"SubObject":[
{
"SubValue":3
}
]
}
]
}
*/
// Verify your JSON if you get any errors here
JsonValue json = JsonValue.Parse(jsonString);
// int test
if (json.ContainsKey("a"))
{
int a = json["a"]; // type already set to int
Console.WriteLine("json[\"a\"]" + " = " + a);
}
// string test
if (json.ContainsKey("b"))
{
string b = json["b"]; // type already set to string
Console.WriteLine("json[\"b\"]" + " = " + b);
}
// object array test
if (json.ContainsKey("c") && json["c"].JsonType == JsonType.Array)
{
// foreach loop test
foreach (JsonValue j in json["c"])
{
Console.WriteLine("j[\"Value\"]" + " = " + j["Value"].ToString());
}
// multi level key test
Console.WriteLine("json[\"c\"][0][\"Value\"]" + " = " + json["c"][0]["Value"].ToString());
Console.WriteLine("json[\"c\"][0][\"Value\"]" + " = " + json["c"][1]["Value"].ToString());
Console.WriteLine("json[\"c\"][1][\"SubObject\"][0][\"SubValue\"]" + " = " + json["c"][1]["SubObject"][0]["SubValue"].ToString());
}
Console.WriteLine();
Console.Write("Press any key to exit.");
Console.ReadKey();
}
}
}
이 도구를 사용하여 클래스를 생성할 수 있는 기반 json:
다음 클래스를 데즈리얼리즈 너회의 json. 예:
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
string json = @"{
'Email': '[email protected]',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);
// [email protected]
참조: nested+json+deserialization+to+c+object+and+using+that+object https://forums.asp.net/t/1992996.aspx? https://www.newtonsoft.com/json/help/html/DeserializeObject.htm
종료기 다음 코드:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("URL");
JArray array = new JArray();
using (var twitpicResponse = (HttpWebResponse)request.GetResponse())
using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
JObject joResponse = JObject.Parse(objText);
JObject result = (JObject)joResponse["result"];
array = (JArray)result["Detail"];
string statu = array[0]["dlrStat"].ToString();
}
Msdn 다음 중 일부 고유 기능을 할 수 있도록 사이트를 뭐하러요 찾고 있는 것 같아요. 윈도 8 을 위해 참고 지정해야 합니다. 아래의 사이트에서 나열되는지 한 예이다.
JsonValue jsonValue = JsonValue.Parse("{\"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"IDs\": [116, 943, 234, 38793]}");
double width = jsonValue.GetObject().GetNamedNumber("Width");
double height = jsonValue.GetObject().GetNamedNumber("Height");
string title = jsonValue.GetObject().GetNamedString("Title");
JsonArray ids = jsonValue.GetObject().GetNamedArray("IDs");
빈다우스그다타.j슨 이름공간이 이용합니다.
내 생각에는 그 해답을 I& # 39, ve seen @MD_Sayem_Ahmed 왔다.
질문, C # 은 어떻게 구문 분석, Json " " 틀렸다니까 싶어하는 것 같다, 그러나 함께 디코딩합니다 Json. # 39 의 경우, Ahmed& 오토메이티드 디코딩합니다 싶어하는 것이 좋다.
ASP.NET 웹 Api 를 할 경우 이를 달성할 수 있는 가장 손쉬운 방법은 객체를 생성하는 데이터 전송 데이터를 포함하는 할당하려는:
public class MyDto{
public string Name{get; set;}
public string Value{get; set;}
}
당신은 단순히 응용 프로그램 추가 / json 헤더입니다 데이터베이스에구성원을 요청 (바이올리니스트 사용하는 경우, 예를 들어). ASP.NET 웹 API 에서 다음과 같이 사용할 수 있습니다.
//controller method -- assuming you want to post and return data
public MyDto Post([FromBody] MyDto myDto){
MyDto someDto = myDto;
/*ASP.NET automatically converts the data for you into this object
if you post a json object as follows:
{
"Name": "SomeName",
"Value": "SomeValue"
}
*/
//do some stuff
}
이 날 내가 어렸을 때 내 웹 Api, 브라운아저씨의 내 인생에 많은 도움을 준 apc® 슈퍼 간편해집니다.
string json = @"{
'Name': 'Wide Web',
'Url': 'www.wideweb.com.br'}";
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
dynamic j = jsonSerializer.Deserialize<dynamic>(json);
string name = j["Name"].ToString();
string url = j["Url"].ToString();
.net 핵심 3.0과 에는 ['시스템스테스t.j슨'] [1] 즉 내장현 JSON 라이브러리를 사용하여 없이 타사 / 직렬화할 데즈리얼리즈 수 있습니다.
Json (es) 을 위해 클래스에 직렬화할 구체화하십시오:
var json = JsonSerializer.Serialize(order);
Json 으로 데즈리얼리즈 수 있는 강력한 입력되었는지 클래스:
var order = JsonSerializer.Deserialize<Order>(json);
그래서 같은 경우 a 클래스 (아래 참조).
public class Order
{
public int Id { get; set; }
public string OrderNumber { get; set; }
public decimal Balance { get; set; }
public DateTime Opened { get; set; }
}
var json = JsonSerializer.Serialize(order);
// creates JSON ==>
{
"id": 123456,
"orderNumber": "ABC-123-456",
"balance": 9876.54,
"opened": "2019-10-21T23:47:16.85",
};
var order = JsonSerializer.Deserialize<Order>(json);
// ==> creates the above class
유의할 것은 ' 자동으로 핸들' 낙타 대문자 '속성' 시스템스테스t.j슨 언약보다는 JSON 사용할 때 자신의 코드의 (하지만 않니다 MVC 모델을 사용할 때 / 바바피 요청률 (binder).
따라서 아래와 같은 경우 '위' 에 JSON 같은 클래스에 데즈리얼리즈 주문하십시오 어졌다면 않을 것입니다.
var json = @"{
""id"": 123456,
""orderNumber"": ""ABC-123-456"",
""balance"": 9876.54,
""opened"": ""2019-10-21T23:47:16.8513874+01:00"",
}";
'' 를 전달하는 데 필요한 해결하십시오 제송즈리얼리제로티언스 매개변수입니다 (죄송합니다. it& # 39 을 구성할 수 없는 이 애플리케이션 wide).
JsonSerializerOptions options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // set camelCase
WriteIndented = true // write pretty json
};
// serialize using options
var json = JsonSerializer.Serialize(order, options);
// deserialize using options
var order = JsonSerializer.Deserialize<Order>(json, options);
net framework 와 닷넷 (.net) '도' 시스템스테스t.j슨 사용할 수 있는 표준 비호환성의 nu 확보하십시오. 패키지 시스템스테스t.j슨
[1]: 보기 = netcore-3.0 https://docs.microsoft.com/en-us/dotnet/api/system.text.json?
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(user)))
{
// Deserialization from JSON
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(UserListing))
DataContractJsonSerializer(typeof(UserListing));
UserListing response = (UserListing)deserializer.ReadObject(ms);
}
public class UserListing
{
public List<UserList> users { get; set; }
}
public class UserList
{
public string FirstName { get; set; }
public string LastName { get; set; }
}