programing

JSON을 사용하여 JSON 데이터를 C#으로 역직렬화합니다.그물

madecode 2023. 3. 14. 22:05
반응형

JSON을 사용하여 JSON 데이터를 C#으로 역직렬화합니다.그물

저는 C#과 JSON 데이터를 다루는 것이 비교적 익숙하지 않기 때문에 지도를 받고 싶습니다.C# 3.0 을 사용하고 있습니다.NET3.5SP1 및 JSON.NET 3.5r6

정의된 C# 클래스가 있으며, 이 클래스는 JSON 구조에서 입력해야 합니다.단, 웹 서비스에서 취득한 엔트리의 모든 JSON 구조체에 C# 클래스 내에 정의되어 있는 모든 가능한 속성이 포함되어 있는 것은 아닙니다.

JObject에서 각 값을 하나씩 선택하여 문자열을 원하는 클래스 속성으로 변환합니다.

JsonSerializer serializer = new JsonSerializer();
var o = (JObject)serializer.Deserialize(myjsondata);

MyAccount.EmployeeID = (string)o["employeeid"][0];

JSON 구조를 C# 클래스로 역직렬화하고 JSON 소스로부터의 손실 데이터를 처리하는 가장 좋은 방법은 무엇입니까?

내 클래스는 다음과 같이 정의됩니다.

  public class MyAccount
  {

    [JsonProperty(PropertyName = "username")]
    public string UserID { get; set; }

    [JsonProperty(PropertyName = "givenname")]
    public string GivenName { get; set; }

    [JsonProperty(PropertyName = "sn")]
    public string Surname { get; set; }

    [JsonProperty(PropertyName = "passwordexpired")]
    public DateTime PasswordExpire { get; set; }

    [JsonProperty(PropertyName = "primaryaffiliation")]
    public string PrimaryAffiliation { get; set; }

    [JsonProperty(PropertyName = "affiliation")]
    public string[] Affiliation { get; set; }

    [JsonProperty(PropertyName = "affiliationstatus")]
    public string AffiliationStatus { get; set; }

    [JsonProperty(PropertyName = "affiliationmodifytimestamp")]
    public DateTime AffiliationLastModified { get; set; }

    [JsonProperty(PropertyName = "employeeid")]
    public string EmployeeID { get; set; }

    [JsonProperty(PropertyName = "accountstatus")]
    public string AccountStatus { get; set; }

    [JsonProperty(PropertyName = "accountstatusexpiration")]
    public DateTime AccountStatusExpiration { get; set; }

    [JsonProperty(PropertyName = "accountstatusexpmaxdate")]
    public DateTime AccountStatusExpirationMaxDate { get; set; }

    [JsonProperty(PropertyName = "accountstatusmodifytimestamp")]
    public DateTime AccountStatusModified { get; set; }

    [JsonProperty(PropertyName = "accountstatusexpnotice")]
    public string AccountStatusExpNotice { get; set; }

    [JsonProperty(PropertyName = "accountstatusmodifiedby")]
    public Dictionary<DateTime, string> AccountStatusModifiedBy { get; set; }

    [JsonProperty(PropertyName = "entrycreatedate")]
    public DateTime EntryCreatedate { get; set; }

    [JsonProperty(PropertyName = "entrydeactivationdate")]
    public DateTime EntryDeactivationDate { get; set; }

  }

해석하는 JSON의 예를 다음에 나타냅니다.

{
    "givenname": [
        "Robert"
    ],
    "passwordexpired": "20091031041550Z",
    "accountstatus": [
        "active"
    ],
    "accountstatusexpiration": [
        "20100612000000Z"
    ],
    "accountstatusexpmaxdate": [
        "20110410000000Z"
    ],
    "accountstatusmodifiedby": {
        "20100214173242Z": "tdecker",
        "20100304003242Z": "jsmith",
        "20100324103242Z": "jsmith",
        "20100325000005Z": "rjones",
        "20100326210634Z": "jsmith",
        "20100326211130Z": "jsmith"
    },
    "accountstatusmodifytimestamp": [
        "20100312001213Z"
    ],
    "affiliation": [
        "Employee",
        "Contractor",
        "Staff"
    ],
    "affiliationmodifytimestamp": [
        "20100312001213Z"
    ],
    "affiliationstatus": [
        "detached"
    ],
    "entrycreatedate": [
        "20000922072747Z"
    ],
    "username": [
        "rjohnson"
    ],
    "primaryaffiliation": [
        "Staff"
    ],
    "employeeid": [
        "999777666"
    ],
    "sn": [
        "Johnson"
    ]
}

사용하다

var rootObject =  JsonConvert.DeserializeObject<RootObject>(string json);

JSON 2 C#에서 클래스를 만듭니다.


Json.NET 매뉴얼:JSON과 JSON의 시리얼화 및 시리얼화 해제네트워크

범용 Deserialize Object 메서드를 사용해 본 적이 있습니까?

JsonConvert.DeserializeObject<MyAccount>(myjsondata);

JSON 데이터 내의 누락된 필드는 NULL인 채로 두어야 합니다.

갱신:

JSON 문자열이 배열인 경우 다음을 수행합니다.

var jarray = JsonConvert.DeserializeObject<List<MyAccount>>(myjsondata);

jarray그럼...List<MyAccount>.

기타 업데이트:

발생하고 있는 예외가 오브젝트 배열과 일치하지 않습니다.직렬화기에 사전 입력에 문제가 있는 것 같습니다.accountstatusmodifiedby소유물.

제외를 시도합니다.accountstatusmodifiedby도움이 되는지 알아보겠습니다.이 경우 해당 속성을 다르게 표현해야 할 수 있습니다.

문서:JSON과 JSON의 시리얼화 및 시리얼화 해제네트워크

다음을 사용할 수 있습니다.

JsonConvert.PopulateObject(json, obj);

여기:jsonjson 문자열입니다.obj는 타겟 오브젝트입니다.참조: 예

주의: obj의 목록 데이터는 삭제되지 않습니다.Populate(),obj'slist member는 원래 데이터와 json 문자열의 데이터를 포함합니다.

bbant의 답변을 바탕으로 원격 URL에서 JSON을 역직렬화하는 완벽한 솔루션입니다.

using Newtonsoft.Json;
using System.Net.Http;

namespace Base
{
    public class ApiConsumer<T>
    {
        public T data;
        private string url;

        public CalendarApiConsumer(string url)
        {
            this.url = url;
            this.data = getItems();
        }

        private T getItems()
        {
            T result = default(T);
            HttpClient client = new HttpClient();

            // This allows for debugging possible JSON issues
            var settings = new JsonSerializerSettings
            {
                Error = (sender, args) =>
                {
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        System.Diagnostics.Debugger.Break();
                    }
                }
            };

            using (HttpResponseMessage response = client.GetAsync(this.url).Result)
            {
                if (response.IsSuccessStatusCode)
                {
                    result = JsonConvert.DeserializeObject<T>(response.Content.ReadAsStringAsync().Result, settings);
                }
            }
            return result;
        }
    }
}

사용 방법은 다음과 같습니다.

ApiConsumer<FeedResult> feed = new ApiConsumer<FeedResult>("http://example.info/feeds/feeds.aspx?alt=json-in-script");

어디에FeedResultXamasoft JSON 클래스 제너레이터를 사용하여 생성된 클래스입니다.

여기 제가 사용한 설정의 스크린샷이 있습니다.웹 버전에서는 설명할 수 없는 이상한 속성명을 사용할 수 있습니다.

Xamasoft JSON 클래스 생성기

나는 내 물건을 잘못 만들었다는 것을 알았다.http://json2csharp.com/을 사용하여 JSON에서 오브젝트 클래스를 생성했습니다.일단 올바른 Oject를 얻으면 문제없이 캐스팅할 수 있었다.노빗, 누브 실수.혹시나 같은 문제가 생길까 봐 추가하려고요

자세한 내용은 일부 클래스 생성기를 온라인으로 확인해 보십시오.하지만, 나는 몇몇 대답들이 유용했다고 믿는다.유용하게 쓰일 수 있는 접근법이 있습니다.

다음 코드는 동적 방식을 염두에 두고 작성되었습니다.

dynObj = (JArray) JsonConvert.DeserializeObject(nvm);

foreach(JObject item in dynObj) {
 foreach(JObject trend in item["trends"]) {
  Console.WriteLine("{0}-{1}-{2}", trend["query"], trend["name"], trend["url"]);
 }
}

이 코드를 사용하면 기본적으로 Json 문자열에 포함된 멤버에 액세스할 수 있습니다.을 사용법 query,trend ★★★★★★★★★★★★★★★★★」url쫑알쫑알하다

사이트도 이용하실 수 있습니다.수업 내용을 100% 신뢰하지는 않지만 이해는 할 수 있습니다.

샘플 데이터가 올바르고 지정된 이름 및 괄호로 둘러싸인 다른 항목이 JS의 배열이라고 가정합니다.이러한 데이터 유형에는 목록을 사용할 수 있습니다.accountstatusexpmaxdate...라고 하는 리스트가 표시됩니다.그러나, 당신의 예에서는 날짜 형식이 잘못되어 있기 때문에, 그 밖에 무엇이 잘못되어 있는지 불명확하다고 생각합니다.

이것은 오래된 게시물이지만, 문제를 메모하고 싶었습니다.

언급URL : https://stackoverflow.com/questions/2546138/deserializing-json-data-to-c-sharp-using-json-net

반응형