JSON反序列化到C#
我看到了很多的JSON反序列化的简单的例子,但是当涉及到任何东西稍微复杂一点,有一个缺乏样品。
I see a lot of simple examples of JSON DeSerialization, but when it comes to anything slightly more complex, there is a lacking of samples.
我期待从GetResponse的API的反序列化对策:
I'm looking at deserializing Responses from GetResponse's API:
简单的如
{
"result" : {
"updated" : "1"
},
"error" : null
}
另:
{
"result" : null,
"error" : "Missing campaign"
}
下面是另一个更复杂的潜在反应:
Here's another more complex potential response:
{
"result" : {
"CAMPAIGN_ID" : { // <-- This value will be different for each Campaign
"name" : "my_campaign_1",
"from_name" : "My From Name",
"from_email" : "me@emailaddress.com",
"reply_to_email" : "replies@emailaddress.com",
"created_on" : "2010-01-01 00:00:00"
}
},
"error" : null
}
对于最后一个,我应该我的对象是什么样子?
我最初只用做这样的事情...
I initially toyed with just doing something like this...
private struct GenericResult {
public string error;
public Dictionary<string, object> result;
}
这会为我所有的反应变量工作,但随后访问该对象的属性我'将不得不投它,如果我没有记错
This will work for all my reponses, but then to access the object's properties I'll have to cast it, if I'm not mistaken.
我想用这样的:
JavaScriptSerializer jss = new JavaScriptSerializer();
var r = jss.Deserialize<GenericResult>(response_string);
// or... if I'm going to use a non-Generic object
var r = jss.Deserialize<GetCampaignResult>(response_string);
修改
获取数据回后,实际的结构具有一个悬挂装置。下面是一个实际的例子:
EDIT
After getting the data back, the actual structure has one hitch. Here's an actual sample:
值
{
"error":null,
"result":
{"ABQz": { // <-- As you can see, this is NOT a class name.
"from_email" : "from@email.com",
"created_on" : "2010-10-15 12:40:00",
"name" : "test_new_subscribers",
"from_name" : "John Smith",
"reply_to_email": "from@email.com"
}
}
}
现在,我不知道这是什么价值将是,我难倒。我想包括值作为广告系列
对象的ID。
Now that I don't know what that value is going to be, I'm stumped. I'd like to include that value as an ID for the Campaign
object.
我看到你的榜样三个对象
I see three objects from your example.
Class CampaignId {
String name ;
String from_Name ;
String from_Email ;
\\ etc
}
Class Result {
CampaignId campaignId ;
}
Class RpcResponse {
String error ;
Result result ;
}
你需要数据成员属性?
Do you need DataMember attributes?
在F#的好文章,我用学习时JSON序列:
的 http://blogs.msdn.com/b/jomo_fisher/archive/2010/03/06/neat-sample-f-and-freebase.aspx
a good article in F# that I used when learning JSON serialization: http://blogs.msdn.com/b/jomo_fisher/archive/2010/03/06/neat-sample-f-and-freebase.aspx
下面的响应发展,你可能想引入一些仿制药:
Developing on the response below, you may want to introduce some generics:
Class CampaignId {
String name ;
String from_Name ;
String from_Email ;
\\ etc
}
Class Result<T> {
<T> data ;
}
Class RpcResponse<T> {
String error ;
Result<T> result ;
}
和intialize以
And intialize the serializer with
JavaScriptSerializer jss = new JavaScriptSerializer();
var r = jss.Deserialize<RpcResponse<CampaignId>>(response_string);
另外一个像样的教程:
another decent tutorial:
http://publicityson.blogspot.com/2010/06/datacontractjsonserializer-versus.html 一>