简体   繁体   中英

How to use a specific field as the name of a json object when using jsonconvert.serializeobject?

So my current output from serializeobject is:

{
"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.

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

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.

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. 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.

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.

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:

"dog" : {
    "myList" : [
        "mystring",
        "mysecondstring"
    ]
}

With a list of objects that looks like this:

object.ID == "dog"
object.myList == ["mystring", "mysecondstring"] //is a List<string>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM