2015-01-13 7 views
2

나는 MVC 애플리케이션을 가지고 있으며 쿼리를 실행하여 테이블 컨텐트를 얻는다. 내가를 디버깅 할 때 내가 테이블 내가 500 Internal Server ErrorDynamicTableEntity를 Json으로 변환

ExceptionMessage: "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'." 

InnerException: 

ExceptionMessage: "Cannot return Binary type for a String typed property." 

을 가져 오기 실행하지만 때

public IEnumerable<DynamicTableEntity> Get(string table) 
{ 
    var storageAccount = CloudStorageAccount.Parse(<StorageConnectionString>); 
    CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); 
    CloudTable table = tableClient.GetTableReference(table); 

    TableQuery<DynamicTableEntity> query = new TableQuery<DynamicTableEntity>() 
     .Where("") 
     .Take(50); 

    return table.ExecuteQuery(query); 
} 

: 내가 다시 클라이언트로 결과를 반환 할 때하지만 난은 ExceptionMessage: "Cannot return Binary type for a String typed property."

컨트롤러 코드를 얻을 "Get"function 나는 모든 데이터가 예상대로 수신되었음을 알았으며 이것은 Json serialization 문제입니다. CloudTableClient PayloadFormatDefaultRequestOptions을 사용하려고 시도했지만 성공하지 못했습니다.

제안 사항?

스택 추적은 :

{ 
Message: "An error has occurred." 
ExceptionMessage: "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'." 
ExceptionType: "System.InvalidOperationException" 
StackTrace: null 
InnerException: { 
Message: "An error has occurred." 
ExceptionMessage: "Error getting value from 'BinaryValue' on 'Microsoft.WindowsAzure.Storage.Table.EntityProperty'." 
ExceptionType: "Newtonsoft.Json.JsonSerializationException" 
StackTrace: " at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType) at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType) at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value) at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding) at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding) at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content) at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()" 
InnerException: { 
Message: "An error has occurred." 
ExceptionMessage: "Cannot return Binary type for a Boolean typed property." 
ExceptionType: "System.InvalidOperationException" 
StackTrace: " at Microsoft.WindowsAzure.Storage.Table.EntityProperty.EnforceType(EdmType requestedType) at Microsoft.WindowsAzure.Storage.Table.EntityProperty.get_BinaryValue() at GetBinaryValue(Object) at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)" 
}- 
}- 
} 
+0

MVC 응용 프로그램에서 사용자의 메서드에서 코드를 시도했지만 문제를 재현 할 수 없습니다. 더 이상 디버깅 할 수 있도록 전체 스택 추적을 공유해주십시오. –

+0

추가되었습니다 .. 감사합니다! – MTZ4

답변

1

불행하게도, DynamicTableEntity 및 EntityProperty 현재 직렬화되지 않습니다. 반면에 POCO 엔티티는 직렬화 가능합니다. TableEntity에서 파생 된 객체로 deserialize하는 경우이 객체는 상자에서 직렬화 할 수 있어야합니다. 하나의 테이블에 저장된 여러 유형을 다루어야하고 조회 결과로 리턴되어야하는 진정으로 이기종 질의를 수행하려는 경우, EntityResolver를 사용하여 적절한 유형으로 분석 할 수 있습니다.

+0

알았어요, 고마워! – MTZ4

0

귀하의 질문에 정확하게 응답하지 않는다는 것을 알고 있지만 xml로 일련 번호를 관리하면 json에서 작동하도록 조정할 수 있습니다.

public static byte[] Serialize(this ITableEntity entity) 
{ 
MemoryStream ms = new MemoryStream(); 
using(var messageWriter = new ODataMessageWriter(new Message(ms), new ODataMessageWriterSettings())) 
{ 
    // Create an entry writer to write a top-level entry to the message. 
    ODataWriter entryWriter = messageWriter.CreateODataEntryWriter(); 
    var writeODataEntity =typeof(TableConstants).Assembly.GetType("Microsoft.WindowsAzure.Storage.Table.Protocol.TableOperationHttpWebRequestFactory") 
     .GetMethod("WriteOdataEntity", BindingFlags.NonPublic | BindingFlags.Static); 

    writeODataEntity.Invoke(null, new object[] { entity, TableOperationType.Insert, null, entryWriter }); 
    return ms.ToArray(); 
}    
} 

public static void Deserialize(this ITableEntity entity, byte[] value) 
{ 
MemoryStream ms = new MemoryStream(value); 
using(ODataMessageReader messageReader = new ODataMessageReader(new Message(ms), new ODataMessageReaderSettings())) 
{ 
    ODataReader reader = messageReader.CreateODataEntryReader(); 
    var readAndUpdateTableEntity = typeof(TableConstants).Assembly.GetType("Microsoft.WindowsAzure.Storage.Table.Protocol.TableOperationHttpResponseParsers") 
     .GetMethod("ReadAndUpdateTableEntity", BindingFlags.NonPublic | BindingFlags.Static); 
    reader.Read(); 
    readAndUpdateTableEntity.Invoke(null, new object[] { entity, reader.Item, 31, null }); 
} 
} 

internal class Message : IODataResponseMessage 
{ 
private readonly Stream stream; 
private readonly Dictionary<string, string> headers = new Dictionary<string, string>(); 

public Message(Stream stream) 
{ 
    this.stream = stream; 
    SetHeader("Content-Type", "application/atom+xml"); 
} 

public string GetHeader(string headerName) 
{ 
    string value; 
    headers.TryGetValue(headerName, out value); 
    return value; 
} 

public void SetHeader(string headerName, string headerValue) 
{ 
    this.headers.Add(headerName, headerValue); 
} 

public Stream GetStream() 
{ 
    return this.stream; 
} 

public IEnumerable<KeyValuePair<string, string>> Headers 
{ 
    get 
    { 
     return this.headers; 
    } 
} 

public int StatusCode 
{ 
    get; 
    set; 
} 
} 
0

내가 JSON 문자열로 DynamicTableEntity 객체 직렬화 및 DynamicTableEntity 객체에 다시 JSON 문자열을 역 직렬화 API를 구현했습니다.

것은 살펴 준비해주십시오

가 // 시리얼에게

DynamicTableEntityJsonSerializer 시리얼 라이저 = 새로운 DynamicTableEntityJsonSerializer()를 인스턴스화 https://www.nuget.org/packages/DynamicTableEntityJsonSerializer/

사용법;

// 직렬화 DynamicTableEntity JSON 문자열로

문자열 serializedEntity = serializer.Serialize (dynamicTableEntity);

// 직렬화 DynamicTableEntity JSON 문자열에서

DynamicTableEntity dynamicTableEntity = serializer.Deserialize (serializedEntity);

의견 환영 :