将DynamicTableEntity转换为Json

时间:2015-01-13 09:27:49

标签: c# asp.net-mvc json azure azure-table-storage

我有一个MVC应用程序,我执行查询以获取表格内容。但是当我尝试将结果返回给客户端时,我得到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);
}

当我执行Get table时,我得到500 Internal Server Error

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."

但是当我调试“获取”功能时,我看到所有数据都按预期收到,这是一个Json序列化问题。我尝试使用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)"
}-
}-
}

4 个答案:

答案 0 :(得分:1)

不幸的是,DynamicTableEntity和EntityProperty目前不可序列化。另一方面,POCO实体是可序列化的。如果您反序列化为从TableEntity派生的对象,那么这应该可以开箱即用。如果要进行真正的异构查询,您必须处理存储在单个表中的不同类型并作为查询结果返回,您可以使用EntityResolver解析为适当的类型。

答案 1 :(得分:1)

我已经实现了一个API,它将DynamicTableEntity对象序列化为Json字符串,并将Json字符串反序列化为DynamicTableEntity对象。

请看看: https://www.nuget.org/packages/DynamicTableEntityJsonSerializer/

<强>用法

//实例化序列化程序

DynamicTableEntityJsonSerializer serializer = new DynamicTableEntityJsonSerializer();

//将DynamicTableEntity序列化为Json字符串

string serializedEntity = serializer.Serialize(dynamicTableEntity);

//从Json字符串反序列化DynamicTableEntity

DynamicTableEntity dynamicTableEntity = serializer.Deserialize(serializedEntity);

欢迎任何评论:)

答案 2 :(得分:0)

我知道它并没有完全回应你的问题,但我设法在xml中序列化,你可以尝试调整它以使它在json中工作。

    View.OnLongClickListener listener = new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View view) {
            view.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            // PRESSED
                            return true; // if you want to handle the touch event
                        case MotionEvent.ACTION_UP:
                            // RELEASED
                            return true; // if you want to handle the touch event
                    }
                    return false;
                }
            });
            return true;
        }

    };

答案 3 :(得分:0)

假设所有值都是String值,这一行就够了

var tables = Record.Properties.Select(x => x.Value.StringValue).ToList();

如果你有更多类型,你可以创建一个 switch 函数来获取每种类型的值。