我有一个 DTO 对象,上面有一个 JsonObject (Data) 属性,这样我就可以存储序列化的对象。
我在下面包含了服务堆栈服务。
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface;
using ServiceStack.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace BuffaloInspection.WebApi.Services
{
[Route("/_layouts/api/test")]
public class ItemDTO
{
public int ID { get; set; }
public string Title { get; set; }
public JsonObject Data { get; set; }
public string DataStr { get; set; }
}
public class TestService : Service
{
public ItemDTO POST(ItemDTO request)
{
var response = new ItemDTO();
response.ID = request.ID;
response.Title = request.Title;
//Failing
response.DataStr = request.Data.ToJson();
response.Data = JsonObject.Parse(response.DataStr);
return response;
}
}
}
我正在使用以下 html 页面调用上述服务。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="SSTest">
<head>
<title>Service Stack Test</title>
</head>
<body>
<div ng-controller="TestCtrl">
<div>ID:<input type="text" name="id" ng-model="item.ID" value="1" /></div>
<div>Title:<input type="text" name="title" ng-model="item.Title" value="Test" /></div>
<div>Length:<input type="text" name="length" ng-model="item.Data.Length" value="10" /></div>
<div>
<button type="button" value="save" ng-click="save(item)">Save</button>
</div>
</div>
<script type="text/javascript" src="components/jquery/jquery.min.js"></script>
<script type="text/javascript" src="components/angular/angular.min.js"></script>
<script type="text/javascript">
'use strict';
var app = angular.module('SSTest', []);
app.controller('TestCtrl', TestCtrl);
function TestCtrl($scope, $http) {
$scope.item = {
ID: 1,
Title: 'Test "',
Data: {
Length: '10 "'
}
};
$scope.save = function (data) {
console.log('before:');
console.log(data);
$http.post("http://localhost:8001/_layouts/api/test/", data).then(function (result) {
console.log('after: ');
console.log(result.data);
$scope.item = result.data;
});
}
}
</script>
</body>
</html>
我加载页面并点击保存。此时客户端对象像这样:
{"ID":1,"Title":"Test\"","Data":{"Length":"10\""}}
当代码到达上面用 //Failing
注释的服务器代码行时,问题是 request.Data
对象包含一个已经转义的字段, ToJson()
调用再次转义,以便在我检索数据时得到 10\\\"
。
request.Data 是一个包含以下信息的 JSON 对象:[0] {[Length, 10\"]}
response.DataStr 现在包含 {"Length":"10\\\""}
回到客户端,我的返回对象现在有额外的转义
有谁知道如何确保特殊字符不被双重转义?
最佳答案
我们有完全相同的情况,我们使用嵌套的 JsonObject 以获得动态对象(尽管受 Json-Schema 限制)。
在我们使用 OrmLite 之前,一切(序列化/反序列化)都运行良好。当 TypeSerializer 反序列化存储的 dto 时,它会向嵌套 JsonObject 中的字符串值添加引号,因此当 Dto 反序列化到线路时,它会获得额外的\"。
为了解决这个问题,我们和您一样,有另一个用于存储目的的 dto,但改为使用:
toStore.DataStr = request.Data.SerializeToString();
response.Data = JsonObject.Parse(toStore.DataStr);
这适用于 Service Stack 3.9.66
关于javascript - 服务堆栈是我的数据中的双重转义引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18501868/