Home > OS >  C# Convert list of string into object
C# Convert list of string into object

Time:09-26

How can I convert a list of strings into an Object?

var flattenList = string.Join(",", jsonVars);
var convJsonVars = JsonConvert.SerializeObject(flattenList);
convJsonVars = "{"   convJsonVars   "}";

var emailData = JsonConvert.DeserializeObject<object>(convJsonVars);

After I Serialize flattenList, these are the results:

"\"tenant_background_color\":\"#c41211\",\"tenant_logo_link\":\"https://imagelink.com\",\"tenant_font_color\":\"#FFFFFF\",\"tenant_name\":\"TNAME\",\"recipient_name\":\"User One\",\"login_link\":\"https://localhost:44330/\",\"verification_link\":\"https://localhost:44330/Link?Key=7b6c12fe-7658-45c5-a5c9-df9900231c6b-f7ea4ae9-3037-4dc5-98dd-e34a33770bb1\""

However, when I try to Deserialize it into an object type and submit it to Sendgrids api, I always get the error that I am passing them a string instead of an Object type.

EDIT:

This is what jsonVars looks like now:

"\"tenant_background_color\":\"#c41211\""

Its a list of strings

CodePudding user response:

when you desterilize a json string , the deserializer find the keys in json and populates fields with same name as json object key. the base model 'object' doesn't have any field of it's own, maybe you are looking for a dictionary<string,object> or a list of expandoObject

CodePudding user response:

You are complicating things unnecessarily by calling JsonConvert.SerializeObject, given that you do not have an object but only properties that need to be joined and enclosed in curly brackets. So:

var convJsonVars = "{"   string.Join(",", jsonVars)   "}";

Now you can deserialize it in two ways that are equivalent in your case:

var emailData = JsonConvert.DeserializeObject<object>(convJsonVars);

or

var emailData = JObject.Parse(convJsonVars);

In both cases the returned object is of type JObject because you did not provide a schema during the Json deserialization. You can still access emailData properties using the indexer, i.e. emailData["tenant_background_color"].

  • Related