0

I have a string

string myString = "KTC|2020|MPD|18/01/2021|I|O|B|ALST|";

I need to convert to the following format.

string convertedJsonString="{"compCode":"KTC","accountYear":"2020","shipmentNumber":"MPD","shipmentDate":"18/01/2021","shipmentType":"I","shipmentCategory":"M","fromLevelCode":"B","fromLocationCode":"ALST"}";

When I tried to write the code like the following,

string[] inputArray = input.Split("|");
string jsonString = @"{"+ " compCode "+ ":" + inputArray[0];
jsonString += "," + "accountYear" + ":" + inputArray[1] + "}";

I am getting the string like the following

{ compCode :KTC,accountYear:2020} Not in the required format.

Can you please give me some idea about how we can achieve this?

uvr
  • 515
  • 4
  • 12
Edwin
  • 11
  • 1
  • Your problem is you do not escape the quotation marks to escape them write: `string jsonString = "{\"compCode\": .... ` – richej Apr 29 '21 at 12:16
  • Converting to object and serializing is the cleanest, but if you want to persist with this approach you should check this out because you are missing the " - https://stackoverflow.com/questions/3458046/how-to-include-quotes-in-a-string – mikelegg Apr 29 '21 at 12:17

2 Answers2

1

Try generating an anonymous class and then serialize it:

var json = new { 
compCode = inputArray[0],
accountYear = inputArray[1],
shipmentNumber = inputArray[2],
shipmentDate=inputArray[3],
shipmentType = inputArray[4],
shipmentCategory=inputArray[5],
fromLevelCode=inputArray[6],
fromLocationCode=inputArray[7]
}

string jsonString = JsonConvert.SerializeObject(json);
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
0

If you already know the key name for each json element you can create a map array and iterate over it.

string[] a = { "compCode", "accountYear" };
var json = "{";
var stringList = "KTC|2020|MPD|18/01/2021|I|O|B|ALST|".Split('|');
for (int i = 0; i < a.length; i++) { json += @",\"{a[i]}\": \"{stringList[i]}\"" ; }
json += "}";
vaggelanos
  • 61
  • 2
  • 7