我有来自Facebook Graph API的JSON响应,如下所示:
{
"name": "XXXXXX YYYYYYY",
"username": "XXXXXX.YYYYYYY",
"email": "XXXXXXYYYYYYY@gmail.com",
"location": {
"id": "110507998976900",
"name": "Someplace, Somestate"
},
"work": [
{
"employer": {
"id": "4647647894784698",
"name": "Some Employer"
},
"location": {
"id": "7489468976968988",
"name": "Someplace, Somestate"
},
"position": {
"id": "4876498697859795",
"name": "Boss"
},
"start_date": "0000-00"
}
],
"id": "1895789769789679",
"picture": {
"data": {
"url": "https://fbcdn-aaaaaaa.net/aaaaaaaa/458768_484784776868_4875876876_q.jpg",
"is_silhouette": false
}
}
我继承了反序列化反序列化的代码,但是我将更复杂的字段(如位置,工作和图片)添加到请求中,现在JSON反序列化器会抛出错误。
我有一个使用DataContractJsonSerializer.ReadObject()的包装类,以及一个如下所示的数据协定类:
[DataContract]
public class FacebookMe
{
private string fbId;
[DataMember]
public string id
{
get { return fbId; }
set { fbId = value; }
}
...
我尝试首先将'work'字段作为字符串添加(当错误开始时),然后添加为Dictionary。到目前为止,我没有运气,我的想法已经不多了。 有什么建议吗?
编辑:
我已经提高了一点。我在类中创建了类来模仿JSON表示法的结构:
[DataContract]
public class Work
{
[DataContract]
public class Employer
{
private string fbEmployerName;
[DataMember]
public string name
{
get { return fbEmployerName; }
set { fbEmployerName = value; }
}
}
private Employer fbEmployer;
[DataMember]
public Employer employer
{
get { return fbEmployer; }
set { fbEmployer = value; }
}
[DataContract]
public class Position
{
private string fbPositionName;
[DataMember]
public string name
{
get { return fbPositionName; }
set { fbPositionName = value; }
}
}
private Position fbPosition;
[DataMember]
public Position position
{
get { return fbPosition; }
set { fbPosition = value; }
}
}
private Work fbWork;
[DataMember]
public Work work
{
get { return fbWork; }
set { fbWork = value; }
}
[DataContract]
public class Picture
{
[DataContract]
public class Data
{
private string fbPictureUrl;
[DataMember]
public string url
{
get { return fbPictureUrl; }
set { fbPictureUrl = value; }
}
private bool fbPictureIsSilhouette;
[DataMember]
public bool is_silhouette
{
get { return fbPictureIsSilhouette; }
set { fbPictureIsSilhouette = value; }
}
}
private Data fbPictureData;
[DataMember]
public Data data
{
get { return fbPictureData; }
set { fbPictureData = value; }
}
}
private Picture fbPicture;
[DataMember]
public Picture picture
{
get { return fbPicture; }
set { fbPicture = value; }
}
}
这导致正确填充所有字段(并且反序列化错误消失)除“work”元素外。 “work”充满了一个对象,它有“雇主”和“位置”字段,它们都是空的。 “work”与“picture”具有相同级别的嵌套数据,“picture”工作得很好。我以同样的方式处理它们。然而一个有效,另一个没有。 他们唯一的区别就是原来的JSON:
work [ {...} ]
picture {...}
“work”有那些额外的括号。知道怎么处理这个吗?
答案 0 :(得分:0)
所以括号代表一个数组。在这种情况下,它是一个“工作”对象的数组,即一个“工作”对象。有一个阵列,因为你可以有更多的雇主,所以更多的“工作”对象。 解决方案是设置数据协定类以期望一系列“工作”项。
private Work[] fbWork;
[DataMember]
public Work[] work
{
get { return fbWork; }
set { fbWork = value; }
}