简体   繁体   中英

Creating a string that uses key value pairs and extract the values from it by key

I have need to store key value pairs in a string. I cannot store them in any other type because the function I am passing these values to takes a param called additionalData and it is of type string.

string data = "FirstName: Mike, LastName: Jones, UserId: 101"

I then need to be able to retrieve each value based on the key.

I could do something like this and then do string.join to create an array when retrieving but prefer not to because I want to use key value:

string data = string.Format("{0}|{1}|{2} ", "Mike", "Jones", 101)
User user = new User {
    FirstName = "Mike",
    LastName = "Jones",
    UserId = 101
};
string userJson = JsonConvert.SerializeObject(user);

You can create User object and parse to json using https://www.nuget.org/packages/Newtonsoft.Json/

And later when you want to deserialize it, you can use the code below:

User user = JsonConvert.DeserializeObject<User>(userJson);

Hope it helps.

传递众所周知的常规格式,该格式可以轻松地进行序列化和反序列化,例如XML或JSON。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM