我正在使用Asp.Net Web API进行一个项目。这个API将使用另一个API,称之为点B。
B点的响应如下所示,并反序列化为Web API,因为我需要更改其中的一些信息,稍后在Web API中再次序列化。
{
"Row": [
{
"key": "MjAxMy0xMQ==",
"Cell": [
{
"column": "Y291bnQ6ZGFlbW9u",
"timestamp": 1385195582067,
"$": "MTE1"
},
{
"column": "Y291bnQ6a2Vybg==",
"timestamp": 1385195582067,
"$": "MQ=="
},
{
"column": "Y291bnQ6dXNlcg==",
"timestamp": 1385195582067,
"$": "MA=="
}
]
}
]
}
这是我的地图。
public class RowEntry
{
[JsonProperty("Row")]
public List<Row> Rows { get; set; }
}
public class Row
{
[JsonProperty("key")]
private string _key;
public string Key
{
get { return Base64Converter.ToUTF8(_key); }
set
{
_key = value;
}
}
[JsonProperty(PropertyName = "Cell")]
public List<Cell> Cells { get; set; }
}
public class Cell
{
[JsonProperty(PropertyName = "column")]
private string _column;
public string Column
{
get
{
return Base64Converter.ToUTF8(_column);
}
set
{
_column = value;
}
}
[JsonProperty(PropertyName = "timestamp")]
public string Timestamp { get; set; }
[JsonProperty(PropertyName = "$")]
private string _value;
public string Value
{
get
{
return Base64Converter.ToUTF8(_value);
}
set
{
_value = value;
}
}
}
在我的控制器中,我有
// Get JSON from point-B
var response = await _client.GetStringAsync(BuildUri(table, startDate, endDate));
// Parse the result into RowEntry object
var results = JsonConvert.DeserializeObject<RowEntry>(response);
// This should return the RowEntry object as JSON as I'm using Web API here
return results;
这应该会返回一个新的JSON,它只包含上面我的类中的元素。然而,它似乎还包含来自B点的第一个请求的JSON。
{
"Row": [
{
"Key": "decoded value here",
"key": "MjAxMy0xMQ==",
"Cell": [
{
"Column": "decoded value here",
"column": "Y291bnQ6ZGFlbW9u",
"timestamp": 1385195582067,
"Value": "decoded value here",
"$": "MTE1"
},
// abbreviated
]
}
]
}
我很困惑,既然我正在序列化RowEntry
,怎么会是这样?我该怎么解决这个问题?
您可以通过将[JsonIgnore]
添加到公共属性来修复此问题,您已经用[JsonProperty]
为其修饰了相应的私有成员变量。Json.Net并不隐含地知道特定的私有成员变量对应于特定的公共属性,所以在序列化时,它将同时包含这两个变量,除非你告诉它不要这样做。
修订类别:
public class Row
{
[JsonProperty("key")]
private string _key;
[JsonIgnore]
public string Key
{
get { return Base64Converter.ToUTF8(_key); }
set { _key = value; }
}
[JsonProperty(PropertyName = "Cell")]
public List<Cell> Cells { get; set; }
}
public class Cell
{
[JsonProperty(PropertyName = "column")]
private string _column;
[JsonIgnore]
public string Column
{
get { return Base64Converter.ToUTF8(_column); }
set { _column = value; }
}
[JsonProperty(PropertyName = "timestamp")]
public string Timestamp { get; set; }
[JsonProperty(PropertyName = "$")]
private string _value;
[JsonIgnore]
public string Value
{
get { return Base64Converter.ToUTF8(_value); }
set { _value = value; }
}
}