更多json c#问题 [英] more json c# issues
问题描述
这是我先前问题的延续.该解决方案适用于当时的工作,但是破坏了我的很多代码.我知道这是一种不好的做法,不要事先确定,而是...你生活和学习.
This is a continuation of a previous question of mine. The solution worked for what I was trying to do at the time but broke a whole lot of my code. I know it was bad practice not to make sure beforehand but yeah... you live and learn.
Anyhoo,这是问:Q:一种简单的序列化c#对象的方法
Anyhoo, here's the Q: an easy way to serialise c# objects
我想知道的是:有什么方法可以让NewtonSoft Library处理这些东西吗?如果是,怎么办?如果没有,建议吗?
What I want to know is: is there any way to get the NewtonSoft Library to handle this stuff? If yes, how? If no, suggestions?
我正在做的事情是使用json与RoR3应用聊天,现在我无法反序列化响应了.这是一些代码:
What i'm doing is chatting to a RoR3 app using json, now I cant deserialise the response. here's a little code:
我从RoR得到的响应如下:
The response i'm getting from RoR looks like:
[{"directory":{"created_at":"2011-07-20T22:29:38Z","drive_info":1,"id":15,"name":"New Drive","parent":0,"size":0,"updated_at":"2011-07-20T22:29:39Z","user":1}}]
我正尝试使用以下方法将其反序列化为Directory对象列表:
I'm trying to deserialise it into a list of Directory objects using:
public static CompositeCollection deserialise<T>(string json)
{
CompositeCollection result = new CompositeCollection();
JArray arr = JArray.Parse(json);
foreach (JObject obj in arr)
{
result.Add(JsonConvert.DeserializeObject<T>(obj.First.First.ToString()));
}
return result;
}
,目录类的相关部分如下所示:
and the relevant part of the directory class looks like:
// [Serializable]
// [DataContract]
public class Directory
{
// [DataMember]
public int id { get; set; }
// [DataMember]
public string name { get; set; }
// [DataMember]
public int parent { get; set; }
// [DataMember]
public int drive_info { get; set; }
// [DataMember]
public int size { get; set; }
// [DataMember]
public int user { get; set; }
// [DataMember]
public string state
{
get
{
/* if (parent == 0)
return _state.identify();
Directory parental;
return parental.state;*/
if (parental != null)
return parental.state;
return _state.identify();
}
set
{
_state = StateFactory.getState(value);
}
}
//[JsonIgnore]
blah...
我大部分时间可以通过取消对[Serializable]的注释来反序列化(有时会出现以下错误:无法将类型为'System.Int32'的对象转换为类型'OffloadUI.Directory'.仍在调查中),并且可以进行序列化通过取消输入[DataContract]和[DataMember]的所有实例.我需要的是可以双向使用的东西.
I can deserialise most of the time by uncommenting [Serializable] (sometimes i get the following error: Object of type 'System.Int32' cannot be converted to type 'OffloadUI.Directory'. still investigating), and I can serialise by uncomenting [DataContract] and all instances of [DataMember]. What i need is something that will work in both directions.
推荐答案
感谢Zootius,我找到了一个有用的指南.这就是我所做的,就像买的一样:
Thanks to Zootius I found a useful guide. Here's what i did, works like a bought one:
[JsonObject(MemberSerialization.OptIn)]
public class Directory
{
[JsonProperty]
public int id { get; set; }
[JsonProperty]
public string name { get; set; }
[JsonProperty]
public int parent { get; set; }
这篇关于更多json c#问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!