Baharun Abu Samah
Baharun Abu Samah

Reputation: 77

How to merge string to JSON using c#

hello i want to post to api but unfortunately there is problem to merge, insert or add the string into it.. please help

merge attempt 1: failed api cant read even 1.

[{"Key":"RatingName","Value":"testing from web"},{"Key":"RatingCode","Value":"1234"},{"Key":"RatingDesc","Value":"1234"},{"Key":"Levels","Value":"[{\"SortOrder\":\"1\",\"LvlName\":\"1\",\"LvlScore\":\"1\",\"LvlDesc\":\"1\"},{\"SortOrder\":\"12\",\"LvlName\":\"12\",\"LvlScore\":\"12\",\"LvlDesc\":\"12\"}]"}]

merge attempt 2 api can read the data but not Levels value: (i just insert string into KeyValuePair and put the Levels value as string) and using FormUrlEncodedContent before post to API

RatingName=testing+from+web&RatingCode=1234&RatingDesc=1234&Levels=%5B%7B%22SortOrder%22%3A%221%22%2C%22LvlName%22%3A%221%22%2C%22LvlScore%22%3A%221%22%2C%22LvlDesc%22%3A%221%22%7D%2C%7B%22SortOrder%22%3A%2212%22%2C%22LvlName%22%3A%2212%22%2C%22LvlScore%22%3A%2212%22%2C%22LvlDesc%22%3A%2212%22%7D%5D

current JSON:

 {
 "RatingName":"testing from web",
 "RatingCode":"1234",
 "RatingDesc":"1234",
 "Levels": "" 
 }

how to insert into Levels with string: (below is literally string not array)

string =  [{"SortOrder":"1",
             "LvlName":"1",
             "LvlScore":"1",
             "LvlDesc":"1"},
           {"SortOrder":"12",
             "LvlName":"12",
             "LvlScore":"12",
             "LvlDesc":"12"}]

my expectation is :

{
     "RatingName":"testing from web",
     "RatingCode":"1234",
     "RatingDesc":"1234"
     "Levels": [{
                 "SortOrder":"1",
                 "LvlName":"1",
                 "LvlScore":"1",
                 "LvlDesc":"1"
                 },
                {
                 "SortOrder":"12",
                 "LvlName":"12",
                 "LvlScore":"12",
                 "LvlDesc":"12"
                 }] 
   }

Upvotes: 0

Views: 79

Answers (1)

Nazar
Nazar

Reputation: 704

Try to use Newtonsoft.Json. Here is an example of code:

using System;
using Newtonsoft.Json.Linq;
                    
public class Program
{
    public static void Main()
    {
        JToken o1 = JToken.Parse("{\"RatingName\":\"testing from web\",\"RatingCode\":\"1234\",\"RatingDesc\":\"1234\",\"Levels\": \"\" }");
        JToken o2 = JToken.Parse("[{\"SortOrder\":\"1\", \"LvlName\":\"1\", \"LvlScore\":\"1\", \"LvlDesc\":\"1\"}, {\"SortOrder\":\"12\", \"LvlName\":\"12\", \"LvlScore\":\"12\", \"LvlDesc\":\"12\"}]");
        
        o1["Levels"] = o2;
        
        Console.WriteLine(o1.ToString());
    }
}

Upvotes: 2

Related Questions