简体   繁体   中英

How to serialize field of type class as main object fields with NewtonSoft json?

Assume that i have these classes:

public class BaseEntity 
{
    public int id;
}

public class A : BaseEntity
{
    public int aField;
    public C c;
}

public class B : BaseEntity
{
    public string bField;
    public C c;
}

public class C : BaseEntity
{
    public string cField;
}

Now, i want to use JSON.Net JsonConverter annotation to serialize C as below when i want to load A or B objects. for example something like this:

[JsonConverter(typeof(JsonConverterCustomImpl))]
public class C
{
    public string cField;
}

and the result of serialized A or B objects should be like this:

// A object
{
   id: 0,
   aField: 0,
   cField: ''
}

// B object
{
   id: 0,
   bField: 0,
   cField: ''
}

I dont know how shoud=ld i implement the JsonConverterCustomImpl class.

UPDATE

i'm used from this answer, also defined FlattenJsonConverter class and set it to JsonAnnotation of A and B , but when i run the project, thi exception was thrown:

An unhandled exception of type 'System.StackOverflowException' occurred in Newtonsoft.Json.dll

在此处输入图片说明

UPDATE

See this below diagram, The C class is Attachment in my application and many of models may be contains that. The Attachment class have a byte[] fileContent field that contains the uploaded file content. So i want to serialize this class as flatten with container class to have a easily access to fileContent in UI side.

I found this way to Serialize C class flatten, but it throws exception when using from JsonConverter in annotation.

NOTE I'm serialize fileContent as a base64 string .

在此处输入图片说明

Found a way to simply serialize an object with Newtonsoft.Json ( http://blog.bitlinkit.com/custom-json/ )

public ActionResult hello()
{
    dynamic d = new JObject();
    d.MetricId = 11;
    string json = Newtonsoft.Json.JsonConvert.SerializeObject(d);
    return Content(json,"JSon");
}

no need to implement the JsonConverterCustomImpl class

In this particular case, you could achieve the result by using inheritance instead of composition. The code would look like this:

public class A : C
{
   public int aField;
}

public class B : C
{
   public string bField;
}

In case there are constraints which rule out this solution, consider editing the question.

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