我正在使用netownsoft json.net来对对象进行序列化,但是一开始它就添加了字符串,我不明白为什么这样做。
Newtonsoft.Json.JsonReaderException:解析值<时遇到意外字符。路径”,第0行,位置0。
public async Task<T> GetDataFromSageService<T>(string url, params string[] args)
where T : class
{
var uri = new Uri(string.Format(url, args));
var response = await _client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(content);
}
return default(T);
}
我正在使用以下内容对位于wcf服务中的端点进行编码。
public string GetWarehouses()
{
DataSet ds = new SqlDa().GetWarehouses();
ds.Tables[0].TableName = "Warehouses";
return JsonConvert.SerializeObject(ds, Formatting.Indented);
}
但是我返回的字符串就是这样
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
{
"Warehouses": [
{
"WarehouseID": 13016489,
"Name": "B",
"Description": "Belfast "
},
{
"WarehouseID": 13016647,
"Name": "B",
"Description": "B"
},
{
"WarehouseID": 13815467,
"Name": "Direct Delivery",
"Description": ""
},
{
"WarehouseID": 1008,
"Name": "PW",
"Description": "Postal Way"
},
{
"WarehouseID": 13016234,
"Name": "H",
"Description": "Hospital"
},
{
"WarehouseID": 13016238,
"Name": "MPC",
"Description": "Clinic"
},
{
"WarehouseID": 13029366,
"Name": "O",
"Description": "Outpatient"
},
{
"WarehouseID": 13815466,
"Name": "Returns",
"Description": ""
}
]
}
</string>
由于某些原因,您可能会看到它作为字符串包含在其中,并且不了解原因。是他们处理数据集的一种方法,以确保将其转换为正确的json。
答案 0 :(得分:0)
如果您不想修改服务器代码,则可以使用regex从响应中提取合法的json字符串。
string content ="your context with xml"
Regex regex = new Regex("<string\\s*xmlns=\".*\">([\\s\\S]*)</string>");
Match match = regex.Match(content);
Response.Write(match.Groups[1].Value);
Newtonsoft.Json.JsonConvert.DeserializeObject(match.Groups[1].Value);