I am trying to create this nested json string in .NET Core2/C# from model but cant quite wrap my head around it:
{
\"SearchByKeywordRequest\":
{
\"keyword\": \""+transistor+"\", \"records\": 0, \"startingRecord\": 0, \"searchOptions\": \"string\", \"searchWithYourSignUpLanguage\": \"string\"
}
}
I referred to this solution but couldnt get it to format properly for my case
Model
public class SearchByKeyword
{
public List<SearchByKeyword> SearchByKeywordRequest { get; set; }
public string keyword { get; set; }
public int records { get; set; } = 10;
public string searchOptions { get; set; } = string.Empty;
public string searchWithYourSignUpLanguage { get; set; } = string.Empty;
}
Method
public string CreateJson(string transistor) {
var obj = new SearchByKeyword() {
SearchByKeywordRequest = new List<SearchByKeyword>()
{
new SearchByKeyword()
{
keyword = transistor
}
}
};
return JsonConvert.SerializeObject(obj);
}
this is the string i end up with
"{
\"SearchByKeywordRequest\":
[ { \"SearchByKeywordRequest\":null, \"keyword\":\"KSA992F\",\"records\":10,\"searchOptions\":\"\",\"searchWithYourSignUpLanguage\":\"\"}],\"keyword\":null,\"records\":10,\"searchOptions\":\"\",\"searchWithYourSignUpLanguage\":\"\"
}"
Now if I try this in method
var obj = new List<SearchByKeyword>()
{
new SearchByKeyword()
{
keyword = transistor
}
};
I get this string
"[{\"SearchByKeywordRequest\":null,\"keyword\":\"KSA992F\",\"records\":10,\"searchOptions\":\"\",\"searchWithYourSignUpLanguage\":\"\"}]"
Updated Model
public class SearchByKeyword
{
[JsonProperty("SearchByKeywordRequest", NullValueHandling = NullValueHandling.Ignore)]
public SearchByKeyword SearchByKeywordRequest { get; set; }
public string keyword { get; set; }
public int records { get; set; } = 10;
}
Updated Method
var obj = new
{
SearchByKeywordRequest = new SearchByKeyword()
{
keyword = transistor
}
};
string json = JsonConvert.SerializeObject(obj);
SearchByKeywordRequestisList<SearchByKeyword>and it will certainly be serialized to an array. for thenull, it is becaues it has no children data.You could add[JsonProperty("SearchByKeywordRequest", NullValueHandling = NullValueHandling.Ignore)]attribute forSearchByKeywordRequestto bypass it