OpenStack OpenStack - 3 months ago 10
C# Question

Substring continue to search until specific character

I am getting a string at the run time. The string is in JSON format( key value pair). One of the key is "

userId
". I need to retrieve the value of
userId
. The problem is I don't know the position of "
userId
" key. The string can look like
{"name":"XX", "userId":"YYY","age":"10"}
or it can look like
{"age":"10", "name":"XX", "userId":"YYY"}
or it can look like this
{"age":"10"}


I am thinking of using
substring()


var index = myString.IndexOf("userId\":\"");
if(index != -1){
myString.Subtring(index, ???)//How to specify the length here
}


I am not sure, how to say continue until you find next
"
(double quote)

Answer

If only userId attribute is planned to use, you can simply declare an object with userId member and deserialize json. any other attributes will be omitted during deserialization.

class UserIDObj
{
   public string UserId { get; set; }
}

var obj = JsonConvert.DeserializeObject<UserIDObj>("{\"name\":\"XX\", \"userId\":\"YYY\",\"age\":\"10\"}");
string usrID = obj.UserId;