c# - How to deserialize string to object (string in format in similar to object notation) -
i have string looks this. it's not json , not xml.
{foo={name=my foo value, active=true, date=20170630}, bar={name=my bar value}, key space={name=foo bar, active=false}} here assumptions:
- objects enclosed
{} - keys can have space in name
- keys separated space , comma (
,) - values assigned keys equal sign
- keys can have multiple values , values enclosed
{}, values inside value separated space , comma (,). example, single key 3 values:{my foo key={one=true, two=true, third value=false}}
my strategy deserialize dictionary<string, object @ first, worry recursion later. suggestions (existing library?) appreciated!
here have
var stringcontenttrimmed = stringcontent.substring(1, stringcontent.length - 2); var objects = stringcontenttrimmed.split(',') .select(x => x.trim()) .where(x => !string.isnullorwhitespace(x)); tldr. split function splitting values, isn't want.
i created method getobjects below returns dictionary<string, string> of top-level objects , raw content inside. method, merge returns nested dictionary calling getvalues extract key-value pairs object content.
using example string, merge method returns this: 
class program { static void main(string[] args) { var str = "{foo={name=foo value, active=true, date=20170630}, bar={name#=my bar value}, key space={name=foo bar, active=false}}"; var values = getobjects(str); dictionary<string, dictionary<string, string>> objects = merge(values); } public static dictionary<string, dictionary<string, string>> merge(dictionary<string, string> input) { var output = new dictionary<string, dictionary<string, string>>(); foreach (var key in input.keys) { var value = input[key]; var subvalues = getvalues(value); output.add(key, subvalues); } return output; } public static dictionary<string, string> getobjects(string input) { var objects = new dictionary<string, string>(); var objectnames = new queue<string>(); var objectbuffer = string.empty; foreach (var c in input) { if (char.equals('{', c)) { if (!string.isnullorempty(objectbuffer)) { var b = objectbuffer.trim('{', '}', ',', ' ', '='); objectnames.enqueue(b); } objectbuffer = string.empty; } if (char.equals('}', c)) { if (objectnames.count > 0) { var b = objectbuffer.trim('{'); var key = objectnames.dequeue(); objects.add(key, b); } objectbuffer = string.empty; } objectbuffer += c; } return objects; } private static dictionary<string, string> getvalues(string input) { var output = new dictionary<string, string>(); var values = input.split(new string[] { ", " }, system.stringsplitoptions.none); foreach (var val in values) { var parts = val.split('='); if (parts.length == 2) { var key = parts[0].trim(' '); var value = parts[1].trim(' '); output.add(key, value); } } return output; } } 
Comments
Post a Comment