0

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) 
0

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

3 Comments

For some reason I thought I was trapped but forgot I could simply create a customer user object and use Json. The thing that I don't like here is that I already have a business entity called User and I don't want to pass all of its properties so I am not sure what I would call this object within my UI layer.
You can also serialize an anonymous type with Json.NET. See newtonsoft.com/json/help/html/CreateJsonAnonymousObject.htm
It depends on which UI layer you are using. In case you are developing web application, one use case is you want to do an ajax call. Another example is you want to expose a web service for native mobile application to call.
1

Pass a well-known, regular format that can easily be serialized and deserialized, like XML or JSON.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.