Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
{"@odata.context":"http://192.168.0.126:49540/odata/$metadata#Edm.String","value":"The Chinese Stai"}

I want to extract the String from the above Json string i.e "The Chinese Stai" which is contained in the variable value

What I have tried:

i have tried many things but i'm getting the error because of the @ symbol at the beginning
Posted
Updated 29-May-20 20:42pm

You should consider a JSON parser and use it to convert that JSON document to a runtime object, JSON.NET would work in this case. Json.NET - Newtonsoft[^]. These parsers would convert your documents properly, without having to worry about invalid data (and if the document is invalid, it would throw exception). Have a look at the JSON schema validator, JSON Schema Validator - Newtonsoft[^], and then try to parse that value in any online JavaScript based JSON parser (JSON.parse()) and you can see for yourself. Are you using your own build parser? The following is a JavaScript sample for this, Edit fiddle - JSFiddle[^]
JavaScript
(function() {
    alert(
    JSON.parse("{\"@odata.context\":\"http://192.168.0.126:49540/odata/$metadata#Edm.String\",\"value\":\"The Chinese Stai\"}")
    .value);
})();

Now as for C#, the code to do that would be,
C#
// You need to use dynamic as type of returned object
// data is that string
dynamic obj = JsonConvert.DeserializeObject(data);

Console.WriteLine(obj.value); // Prints: The Chinese Stai

If everything goes right, you will see that output. I wrote an article on the topic of JSON and C#, you should consider reading that, From zero to hero in JSON with C#[^]. It also explains the process of extracting dynamically built JSON documents in dynamic objects in C#, see the comments to that article.
 
Share this answer
 
v2
Comments
CPallini 11-Sep-17 8:18am    
5.
Afzaal Ahmad Zeeshan 11-Sep-17 8:22am    
Thank you. I added a bit more explanation to the answer which I believe was missed, please have a look.
Karthik_Mahalingam 11-Sep-17 23:45pm    
5
Afzaal Ahmad Zeeshan 12-Sep-17 7:40am    
Thank you, Karthik, but it seems like you forgot to click the 5 stars. :-)
Karthik_Mahalingam 12-Sep-17 9:08am    
yeah :) , upvoted now..
This article will help: Working with JSON in C# & VB[^] - Newtonsoft's Json.Net has the JsonProperty attribute - this will handle your "@" problem without the need to use Dynamic classes. The article also has a number of useful links, some to how to generate classes from JSON data - JsonUtils is my favorite.
 
Share this answer
 
Comments
Karthik_Mahalingam 11-Sep-17 23:45pm    
5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900