2011-02-24 5 views
1

JSON 문자열을 매개 변수로받는 웹 서비스가 있습니다. 내 웹 메서드의 매개 변수가 제네릭 형식의 '개체'일 때만 성공적으로 보낼 수있었습니다.어떻게이 JSON 객체를 직렬화 할 수 있습니까?

이 일반 개체를 문자열이나 사용자 지정 개체로 serialize 할 수 있습니까? 이 메소드의 매개 변수 유형을 수정해야합니까? 어떤 도움이라도 굉장합니다.

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public string StoreDataOut(object json) 
{ 
    //serialization magic 
} 

이이 웹 메소드에 전달되는 테스트 JSON입니다 : 여기

는 웹 방법

{ 
    "uid":"1234abcd", 
    "application":"Application Name", 
    "eventName":null, 
    "clienttoken":"Test Client", 
    "version":"1.0.0", 
    "datetime":"1/1/2011 12:00 AM", 
    "data":[ 
     { 
      "id":"alpha_123", 
      "question":"ronunciations in pre-classical times or in non-Attic dialects. For det", 
      "answer":"nunciations " 
     }, 
     { 
     "id":"beta_456", 
     "question":"official documents such as laws an", 
     "answer":"or modif" 
     }, 
     { 
      "id":"gamma_789", 
      "question":" maintained or modified slightly to fit Greek phonology; thus, ?", 
      "answer":"iation of Attic" 
     }, 
     { 
      "id":"delta_098", 
      "question":"econstructed pronunciation of Attic in the late 5th an", 
      "answer":"unciation of " 
     }, 
     { 
      "id":"epsilon_076", 
      "question":"erent stylistic variants, with the descending tail either going straight down o", 
      "answer":"Whole bunch" 
     }, 
     { 
      "id":"zeta_054", 
      "question":"rough breathing when it begins a word. Another diacritic use", 
      "answer":"other dia" 
     } 
    ] 
} 

답변

2

당신은 다음과 같이 클래스가 필요하고 사용이 그 유형으로 귀하의 webmethod 대신에 개체.

class JsonDTO 
{ 

    public JsonDTO() 
    { 
    data = new List<data>(); 
    } 
    public string uid {get; set;} 
    public string application {get;set} 
    public string eventName {get; set;} 
    public string clienttoken {get;set} 
    public string version {get;set;} 
    public string @datetime {get; set;} 
    public List<data> data {get; set;} 



} 

public class data 
{ 
    public string id {get; set;} 
    public string question {get; set;} 
    public string answer {get; set;} 
} 
+0

그냥 작동할까요?! 멋지다 .. 아프다. – Nick

+0

이것은 매우 가까이에 도착하지만 .. "데이터"목록에 채워지지 않습니다. – Nick

+0

신경 쓰지 마 :) 감사합니다. .. asp.net이 그런 속성을 매핑하는 것을 전혀 몰랐습니다. – Nick

2

당신 올바르게 닷넷 프레임 워크를 웹 메소드 서명은 다음과 같습니다 그래서 대부분의 개체를에는 직렬화 할 수 있어야한다 : 나는 특정 개체가 probelms을 가지고 것으로 나타났습니다

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public string StoreDataOut(MyClass input); 

그러나 함께, 그래서 내 fallback 메서드는 (직렬화 된 JSON됩니다) 대신 문자열을 받아들이고 JavaScriptSerializer 클래스 나 Json.Net 같은 JSON 직렬화 라이브러리를 사용하여 직접 deserialize하는 것입니다.

내가 우리를 위해 deserialistion을 처리하는 래퍼 방법으로 "실제"방법을 별도로 JavaScriptSerializer 클래스를 사용하여 객체를 deserialising의 예입니다

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public string StoreDataOut(string input) 
{ 
    var serialiser = new JavaScriptSerializer(); 
    MyClass deserialisedInput = serialiser.Deserialize<MyClass>(input); 
    return (StoreDataOutImpl deserialisedInput); 
} 

private string StoreDataOutImpl(MyClass input); 

이렇게하면되는 유연성을 제공 JavaScriptConverters을 사용하거나 완전히 다른 라이브러리 (예 : Json.Net)를 사용하여 직렬화를 제어 할 수 있습니다.

입력 된 JSON을 수신하기 위해 올바르게 형식화 된 클래스 MyClass이 있어야합니다. 그렇게하지 않으면 serializer에서 serialize 된 JSON 객체의 속성에 해당하는 키 - 값 쌍을 포함하는 사전을 출력 할 수 있습니다.

관련 문제