简体   繁体   中英

Parsing selected JSON key value pair in C#

I have a JSON Input and i need to store specific key value from it.

For eg: Lets says, i have input like below

I/P:

{
 "CLICKS": "0.14",
 "IMPRESSIONS": 0,    
 "SOCIAL": 0,    
 "REACH": 0,    
 "ACTIONS": 0  
}

O/P:(In String Form)

{ "CLICKS": "0.14"}

I am using JObject

var finalJsonData = JObject.Parse(jsonInStringForm);

I can try with JToken or SelectToken, but that will make it more complex, thats why looking for more optimized solution or inbuilt feature in C# libs.

Do you want something like this?

JObject input = JObject.Parse(@"{
 ""CLICKS"": ""0.14"",
 ""IMPRESSIONS"": 0,    
 ""SOCIAL"": 0,    
 ""REACH"": 0,    
 ""ACTIONS"": 0  
}");
JProperty find = input.Property("CLICKS");
JObject output = new JObject(find);
string s = output.ToString();

If you want to remove single property:

JObject input = JObject.Parse(@"{
 ""CLICKS"": ""0.14"",
 ""IMPRESSIONS"": 0,    
 ""SOCIAL"": 0,    
 ""REACH"": 0,    
 ""ACTIONS"": 0  
}");
JProperty find = input.Property("IMPRESSIONS");
find.Remove();
string s = input.ToString().Dump();

Copy your JSON code { "CLICKS": "0.14", "IMPRESSIONS": 0,
"SOCIAL": 0,
"REACH": 0,
"ACTIONS": 0
}
{ "CLICKS": "0.14", "IMPRESSIONS": 0,
"SOCIAL": 0,
"REACH": 0,
"ACTIONS": 0
}
{ "CLICKS": "0.14", "IMPRESSIONS": 0,
"SOCIAL": 0,
"REACH": 0,
"ACTIONS": 0
}
Then inside Visual Studio create an class from the pasted JSON data.
Edit -> Paste Special -> Paste JSON as Classes

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