Brian
Brian

Reputation: 1989

How would I create the data models for my JSON string in .NET Core 5.x

I am trying to follow along with this:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-5.0#make-post-put-and-delete-requests

This is my JSON string I need to send to the API endnpoint:

{
    "search":
        [
            {"queryString":"test"},
            {"queryParameter01": "blah blah blah"},
            {"queryParameter02": "blah blah blah"},
            {"queryParameter03": "blah blah blah"}
        ]
}

For my data models, I have this:

public class SearchRequest
{
    public String search{ get; set; }
}

public class QueryStringRequest
{
    public String queryString { get; set; }
}

public class QueryParameterRequest
{
    public String queryParameter { get; set; }
}

I know I need an array of QueryStringRequest and QueryParameterRequest objects in the SearchRequest object, but I can't figure it out. Also, does the SearchRequest object return a String or something else?

I ask because I will be using JsonSerializer.Serialize later to turn my object into a JSON string to send to the API endpoint, so it seems "pointless" to return a string to serialize into a string.

Upvotes: 0

Views: 239

Answers (1)

Yiyi You
Yiyi You

Reputation: 18209

As your json shows each object is different in your "search" array,and array can only have one type model,you cannot have a json as showing in your question.You can try to use dictionary.Here is a model:

public class JsonModel { 
        public Dictionary<string, string> search { get; set; }
    }

And your Json will be like:

{
    "search":
        {
            "queryString":"test",
            "queryParameter01": "blah blah blah",
            "queryParameter02": "blah blah blah",
            "queryParameter03": "blah blah blah"
        }
}

So that you can have many different keys and values in "search".

Upvotes: 1

Related Questions