简体   繁体   中英

c# Web api nested json field change dynamically

I need to return a json object from my web api. The problem is there is a nested object. in that object column name changed dynamically and also nested object has only cursive bracket. Sample json given below. Any one know how to solve this issue please help.

[

   {

      src: 'https://www.test.com/line.jpg',

      screen: 'PLAYLIST_SCREEN',

      data: {

        playlist_id: '751becbe-5546-4728-8738-e96238be4749'

      }

    },

    {

      src: 'https://www.test.com/linet-2.jpg',

      screen: 'VIDEO_SCREEN',

      data: {

        video_id: '40541a11-e29d-4852-91c8-c2aac76d64c9'

      }

    },

    {

      src: 'https://www.test.com/line_3xl.jpg?impolicy=HomeHero',

      screen: 'SEARCH_SCREEN',

      data: {

        query: 'برنامج صباح الخير يا كويت'

      }

    }

]

Assuming data is coming from a C# object, you can use this attribute to skip serialization of any properties that are null:

[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]

Here is an example of what data might look like in C#:

public class data
{
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
    [JsonPropertyName("playlist_id")]
    public string? PlaylistId { get; set; }

    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
    [JsonPropertyName("video_id")]
    public string? VideoId { get; set; }

    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
    [JsonPropertyName("query")]
    public string? Query { get; set; }
};

The Microsoft documentation has more examples of usage.

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