[英]How to use a specific field as the name of a json object when using jsonconvert.serializeobject?
So my current output from serializeobject is: 所以我当前来自serializeobject的输出是:
{
"ID": "dog-1",
"fed": [
"2016/05/19T01:00:00Z"
]
},
"ID" is a string in the object I am trying to serialize, and "fed" is a List of string. “ ID”是我要序列化的对象中的字符串,“ fed”是字符串列表。
My question is, can I use some kind of attribute to make it so that I get this instead? 我的问题是,我可以使用某种属性来代替它吗?
"dog-1" : {
"fed": [
"2016/05/19T01:00:00Z"
]
},
I'm using newtonsoft JsonConvert.SerializeObject 我正在使用newtonsoft JsonConvert.SerializeObject
Short answer: no, you can't 简短的回答:不,你不能
You're serializing an object, this is, translating it's structure to a string whose depicts it's attributes and values. 您正在序列化一个对象,这是将其结构转换为描述其属性和值的字符串。
However, you can identify the structure you want to obtain serialized, migrate your object from it's original structure to the one you need and then serialize it. 但是,您可以标识要序列化的结构,将对象从其原始结构迁移到所需的结构,然后序列化。
In your example, you have an object which seems something like this: 在您的示例中,您有一个看起来像这样的对象:
class yourObject {
public string ID;
public Date fed;
}
But you want to serialize to something that feels more like a dictionary that stablish a direct relationship between a string and a Date. 但是您想要序列化为更像字典的东西,该字典稳定了字符串和Date之间的直接关系。
Maybe you can create something similar to this: 也许您可以创建类似于以下内容的东西:
class yourOtherObject {
public Date fed;
}
And load your original object in a fashion like this: 并以如下方式加载原始对象:
yourObject originalData = new yourObject("dog-1", "2016/05/19T01:00:00Z");
yourOtherObject originalDataDate = new yourOtherObject();
originalDataDate.fed = originalData.fed;
KeyValuePair<string, yourOtherObject> serializableData = new KeyValuePair<string, yourOtherObject>(originalData.ID, originalDataDate);
Now, if you serialize serializableData , you should obtain the result you're seeking. 现在,如果序列化serializableData ,则应获得所需的结果。 Just encapsulate the idea into a class, make ad-hoc constructors and methods to transfer data from yourObject to this class and from this class to yourObject and you'll be able to get the translation.
只需将想法封装到一个类中,创建临时的构造函数和方法,即可将数据从yourObject传输到此类,再从该类传输到yourObject,则可以获取翻译。
Other option is to add a method which makes the specific serialization into yourObject class, but this tends to be much more work on the long run. 另一个选择是添加一个方法,使特定的序列化进入yourObject类,但是从长远来看,这往往会花费更多的工作。
Found a usable solution. 找到了可用的解决方案。
var x = new List<MyClass>();
JsonConvert.SerializeObject(x.ToDictionary(x => x.ID));
And this will create a list of Json with each object looking like this: 这将创建一个Json列表,每个对象如下所示:
"dog" : {
"myList" : [
"mystring",
"mysecondstring"
]
}
With a list of objects that looks like this: 带有如下所示的对象列表:
object.ID == "dog"
object.myList == ["mystring", "mysecondstring"] //is a List<string>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.