wcf에서 raw json(문자열)을 반환하는 중
자체 JSON을 구축하여 서비스에서 문자열을 반환하고 싶습니다.다음 코드는 다음과 같습니다.
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
public string GetCurrentCart()
{
//Code ommited
string jsonClient = null;
var j = new { Content = response.Content, Display=response.Display, SubTotal=response.SubTotal};
var s = new JavaScriptSerializer();
jsonClient = s.Serialize(j);
return jsonClient;
}
수신한 응답에는 c# 문자열에 "s"를 작성하기 위해 사용되는 ""가 포함되어 있습니다.
다음은 답변입니다.
"{\"Content\":\"\\r\\n\\u003cdiv\\u003e\\r\\n\\u003cinput type=\\\"hidden\\\" name=\\\"__VIEWSTATE\\\" id=\\\"__VIEWSTATE\\\" value=\\\"\/wEPDwUBMA9kFgJmD2QWAmYPZBYGAgMPFgIeBFRleHQFKFlvdSBoYXZlIG5vIGl0ZW1zIGluIHlvdXIgc2hvcHBpbmcgY2FydC5kAgUPFgIeB1Zpc2libGVoZAIHDxQrAAIPFgIfAWhkZGQYAQUMY3RsMDEkbHZDYXJ0D2dkoWijqBUJaUxmDgFrkGdWUM0mLpgQmTOe8R8hc8bZco4=\\\" \/\\u003e\\r\\n\\u003c\/div\\u003e\\r\\n\\r\\n\\u003cdiv class=\\\"block block-shoppingcart\\\"\\u003e\\r\\n \\u003cdiv class=\\\"title\\\"\\u003e\\r\\n \\u003cspan\\u003eShopping Cart\\u003c\/span\\u003e\\r\\n \\u003c\/div\\u003e\\r\\n \\u003cdiv class=\\\"clear\\\"\\u003e\\r\\n \\u003c\/div\\u003e\\r\\n \\u003cdiv class=\\\"listbox\\\"\\u003e\\r\\n You have no items in your shopping cart.\\r\\n \\r\\n \\r\\n \\u003c\/div\\u003e\\r\\n\\u003c\/div\\u003e\\r\\n\",\"Display\":\"You have no items in your shopping cart.\",\"SubTotal\":null}"
값이 올바르게 인코딩되고 있지만 json 자체의 형식이 올바르지 않습니다.이 \가 원인입니다.
"s" 앞에 \"가 없는 문자열을 반환하려면 어떻게 해야 합니까?
현재 웹 메서드는String
와 함께ResponseFormat = WebMessageFormat.Json
따라서 코드에서는 문자열의 JSON 인코딩이 사용됩니다.json.org에 대응하고 있기 때문에 문자열 내의 모든 이중 따옴표는 백슬래시를 사용하여 이스케이프됩니다.따라서 현재 이중 JSON 인코딩을 사용하고 있습니다.
모든 종류의 데이터를 반환하는 가장 쉬운 방법은 의 출력 유형을 변경하는 것입니다.GetCurrentCart()
웹 메서드Stream
또는Message
(출처:System.ServiceModel.Channels
대신 )를 사용합니다.String
.
코드 예에 대해서는, 을 참조해 주세요.
- Carlos Figueira MSDN 블로그 투고, 'WCF "Raw" 프로그래밍 모델',
- MSDN의 "스트리밍 활성화 방법" 및
- MSDN의 "WCF REST 프로그래밍 모델을 사용하여 임의의 데이터를 반환하는 서비스 작성 방법"
어떤 버전의 의 질문에는 포함되어 있지 않기 때문입니다.사용하고 있는 NET에서는, 범용(가장 간단한) 방법을 사용하는 것을 추천합니다.
public Stream GetCurrentCart()
{
//Code ommitted
var j = new { Content = response.Content, Display=response.Display,
SubTotal=response.SubTotal};
var s = new JavaScriptSerializer();
string jsonClient = s.Serialize(j);
WebOperationContext.Current.OutgoingResponse.ContentType =
"application/json; charset=utf-8";
return new MemoryStream(Encoding.UTF8.GetBytes(jsonClient));
}
Oleg가 제안한 방법을 사용해 보았지만, 대량의 데이터에 대해 이 방법을 사용했을 때 JSON 문자열 끝에 늘키워드가 부가되어 있었습니다.
예: 데이터가 많은 json의 경우 {"JsonExample":xxxxx"}null
http://wcf.codeplex.com/workitem/67 에서 이 문제를 해결하기 위한 솔루션을 찾았습니다.개체를 받아들여 Pure Json 출력을 반환하는 다음 함수를 작성했습니다.그래서 메인 메서드에서 오브젝트를 반환하기 전에 아래 메서드로 호출합니다.
public HttpResponseMessage ReturnPureJson(object responseModel)
{
HttpResponseMessage response = new HttpResponseMessage();
string jsonClient = Json.Encode(responseModel);
byte[] resultBytes = Encoding.UTF8.GetBytes(jsonClient);
response.Content = new StreamContent(new MemoryStream(resultBytes));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
return response;
}
라이브러리를 사용하여 JSON 개체 또는 동적(Expando Object)을 직렬화할 것을 권장합니다.
내 경우 항상 "{}"을(를) 받는 것과 같은 null 값 문제를 피할 수 있습니다.JsonConvert.SerializeXXX
{aa:bb}을(를) {key:aa, value:bb}로 확장합니다.JavaScriptSerializer
여기 전체 샘플은 아래와 같습니다.
인터페이스:
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "json/GetCurrentCart")]
Stream GetCurrentCart(MyRequestParam Param);
구현:
public Stream GetCurrentCart(MyRequestParam Param)
{
//code omitted
dynamic j = new System.Dynamic.ExpandoObject();
j.Content = response.Content;
j.Display = response.Display;
j.SubTotal = response.SubTotal;
string s = Jil.JSON.SerializeDynamic(j);
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
return new MemoryStream(Encoding.UTF8.GetBytes(s));
}
훌륭했습니다(Oleg Response).모두 WebOperationContext 행을 추가해야 합니다.현재의.Outgoing Response.ContentType = "application/json; charset=utf-8";
삭제 시 결과는 file로 다운로드 됩니다.
언급URL : https://stackoverflow.com/questions/3078397/returning-raw-json-string-in-wcf
'programing' 카테고리의 다른 글
각도 연장기 재스민 테스트에서의 console.log 출력 표시 (0) | 2023.03.23 |
---|---|
스프링 부트 시 Tomcat을 사용한HTTP2의 이니블화 (0) | 2023.03.23 |
Angular 앱을 배포하려면 어떻게 해야 합니까? (0) | 2023.03.23 |
$watch vs ng-change, ng-checked 등에 의한 각도 트리거 변경 (0) | 2023.03.23 |
log4j는 JSON 형식을 지원합니까? (0) | 2023.03.23 |