Reputation: 2295
Hi How do I retrieve the number from the following string,
{"number":100,"data":[test]}
The number could be of any length.
I used the following code. but it gives and error message
strValue.Substring((strValue.IndexOf(":")+1), (strValue.IndexOf("data")));
the output comes like
100,"data":[
Thanks,
Upvotes: 1
Views: 396
Reputation: 8047
Your attempt is close. There are two (possibly three issues) I found.
SubString
to something, but if you're not, the end result is that strValue
remains unchanged.Overall, the result of your current call to string.Substring
is returning 100,"data":[tes
. (and as far as I can see, it's not storing the result).
Try the following code:
string justTheNumber = null;
// Make sure we get the correct ':'
int startIndex = strValue.IndexOf("\"number\":") + 9;
// Search for the ',' that comes after "number":
int endIndex = strValue.IndexOf(',', startIndex);
int length = endIndex - startIndex;
// Note, we could potentially get an ArguementOutOfRangeException here.
// You'll want to handle cases where startPosition < 0 or length < 0.
string justTheNumber = strValue.Substring(startIndex, length);
Note: This solution does not handle if "number":
is the last entry in the list inside your string, but it should handle every other placement in it.
If your strings get more complex, you could try using Regular Expressions to perform your searches.
Upvotes: 3
Reputation: 10219
As noted by Jon, your input string seems to be a JSON string which needs to be deserialized. You can write your own deserializer, or use an existing library, such as Json.NET. Here is an example:
string json = @"[
{
""Name"": ""Product 1"",
""ExpiryDate"": ""\/Date(978048000000)\/"",
""Price"": 99.95,
""Sizes"": null
},
{
""Name"": ""Product 2"",
""ExpiryDate"": ""\/Date(1248998400000)\/"",
""Price"": 12.50,
""Sizes"": null
}
]";
List<Product> products = JsonConvert.DeserializeObject<List<Product>>(json);
Upvotes: 3
Reputation: 1754
Parsing JSON spring in that way is very bad practice as everything is hardcoded. Have you though of using 3rd party library for parsing JSON strings, like Newtonsoft JSON.
Upvotes: 2
Reputation: 51369
It looks like your input string is JSON. Is it? If so, you should use a proper JSON parser library like JSON.NET
Upvotes: 10