Retrieve boolean value from json data containing string key/values - c#

I have the following json data being returned to me and I need to check if the user has the 'public_actions' permission granted or not.
{"data":[{"permission":"installed","status":"granted"},{"permission":"public_profile","status":"granted"},{"permission":"email","status":"granted"},{"permission":"publish_actions","status":"granted"}]}
Having not really done anything with json data before, I'm not sure the recommended approach to essentially arrive at a true or false (whether that particular permission has been granted or not).

Json.NET is a popular high-performance JSON framework for .NET.
This how I read json string using Newtonsoft.Json.dll:
var json = #"{
data: [
{
permission: 'installed',
status: 'granted'
},
{
permission: 'public_profile',
status: 'granted'
},
{
permission: 'email',
status: 'granted'
},
{
permission: 'publish_actions',
status: 'granted'
}
]
}";
JObject jObjects = JObject.Parse(json);
foreach (KeyValuePair<String, JToken> kvpParent in jObjects)
{
var sMainKey = kvpParent.Key;
var objects = JArray.Parse(kvpParent.Value.ToString());
foreach (JObject jObj in objects)
{
foreach (KeyValuePair<String, JToken> kvp in jObj)
{
var sKey = kvp.Key; //permission
var sValue = (String)kvp.Value; //installed
}
}
}
Each KeyValuePair gets 2 count that is for permission and status keys.

Related

C# Get JSON Keys from Array without Model

I have a JSON file
{
"RandonName": [
{
"RandomKey1": "Data",
"RandomKey2": "Data",
"RandomKey3": "Data",
"RandomKey4": "Data",
"RandomKey5": "Data"
},
{
"RandomKey1": "Data",
"RandomKey2": "Data",
"RandomKey3": "Data",
"RandomKey4": "Data",
"RandomKey5": "Data"
}
]
}
My Deserializer
JsonTextReader JTR = new JsonTextReader(stringReader);
JsonSerializer JS = new JsonSerializer();
var dictionary = JS.Deserialize(JTR) as IEnumerable<KeyValuePair<string, JToken>>;
My Print, output is RandonName
foreach(KeyValuePair<string, JToken> pair in sourceRoot)
{
Console.WriteLine(pair.Key);
}
Can I get somehow all Key names inside the array?
JsonSerializer.Deserialize() is a static method. You don't need to create instance for JsonSerializer.
Meanwhile JToken is from Newtonsoft.Json. I think would be great not to mix up with System.Text.Json and Newtonsoft.Json.
And deserialize as Dictionary<string, List<Dictionary<string, string>>> type.
Dictionary<string, List<Dictionary<string, string>>> dictionary = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(JTR);
// Iterate for first item in RandonName dictionary
foreach (KeyValuePair<string, string> kvp in dictionary["RandonName"][0])
{
Console.WriteLine(kvp.Key);
Console.WriteLine(kvp.Value);
}
// Iterate for all items in RandonName dictionary
foreach (var items in dictionary["RandonName"])
{
foreach (KeyValuePair<string, string> kvp in items)
{
Console.WriteLine(kvp.Key);
Console.WriteLine(kvp.Value);
}
}
Sample .NET Fiddle
To get all Keys (from the first item):
dictionary["RandonName"][0].Keys
To get all keys from every item in the list:
using System.Linq;
dictionary["RandonName"].SelectMany(x => x.Keys).ToList();
string json = #"{
'RandonName': [
{
'RandomKey1': 'Data',
'RandomKey2': 'Data',
'RandomKey3': 'Data',
'RandomKey4': 'Data',
'RandomKey5': 'Data'
},
{
'RandomKey1': 'Data',
'RandomKey2': 'Data',
'RandomKey3': 'Data',
'RandomKey4': 'Data',
'RandomKey5': 'Data'
}
]
}
";
Console.WriteLine(
JObject.Parse(json)["RandonName"][0].Children<JProperty>().Select(x => x.Name));
Will print out:
RandomKey1
RandomKey2
RandomKey3
RandomKey4
RandomKey5
The key to the one-liner is to cast the children of the first JObject to JProperty.
If you need only just the property names from the first object then you can take advantage of Json.NET's Linq
var semiParsedJson = JObject.Parse(json);
var collection = (JArray)semiParsedJson["RandonName"];
var firstObject = (JObject)collection.First();
foreach (var property in firstObject.Properties())
{
Console.WriteLine(property.Name);
}

Iterating JObject Keys

I have the following JObject as return by https://gate.io/api2#trade API. How do I iterate through each key which is a separate coin also get its value.
I tried to parse it using Newtonsoft JObject Parse like this:
var coinData = JObject.Parse(#"{
""result"": ""true"",
""available"": {
""BTC"": ""0.83337671"",
""LTC"": ""94.364"",
""ETH"": ""0.07161"",
""ETC"": ""82.35029899""
},
""locked"": {
""BTC"": ""0.0002"",
""YAC"": ""10.01""
}
}")["available"];
foreach (JToken item in coinData)
{
item.Key
}
but then JToken doesn't give access to key values. I don't know how to further parse it.
JSON received from gateio api:
{
"result": "true",
"available": {
"BTC": "0.83337671",
"LTC": "94.364",
"ETH": "0.07161",
"ETC": "82.35029899"
},
"locked": {
"BTC": "0.0002",
"YAC": "10.01"
}
}
EDIT: Should I break it with ':' while iterating in loop? This is working if i break it and replace quotes.
foreach (JToken item in coinData)
{
var data = item.ToString().Replace("\"", String.Empty).Split(':');
}
var data has two parts, 1 => coin name, 2 => balance.
Is there any other legit way?
JToken is base class for all types of json tokens. In your case though you want only json properties, so you need to filter by more narrow type - JProperty. You can filter to include only property tokens like this:
foreach (var item in coinData.OfType<JProperty>()) {
string coinName = item.Name;
// to parse as decimal
decimal balance = item.Value.Value<decimal>();
// or as string
string balanceAsString = item.Value.Value<string>();
}
I would suggest being very explicit about expecting the result of "available" to be another object, by casting to JObject. You can then call Properties() to get its properties, each as a JProperty. Here's a complete example to demonstrate:
using System;
using Newtonsoft.Json.Linq;
class Program
{
public static void Main()
{
string json = #"{
'result': 'true',
'available': {
'BTC': '0.83337671',
'LTC': '94.364',
'ETH': '0.07161',
'ETC': '82.35029899'
},
'locked': {
'BTC': '0.0002',
'YAC': '10.01'
}
}".Replace('\'', '"');
JObject root = JObject.Parse(json);
JObject coins = (JObject) root["available"];
foreach (JProperty property in coins.Properties())
{
string name = property.Name;
string value = (string) property.Value;
Console.WriteLine($"Name: {name}; Value: {value}");
}
}
}

How to get only the root name in Json

Say I have a Json as below:
{
"Records123": {
"-count": "1",
"-count2": "2",
"-count3": "4",
"Metadata": {
"value": 2,
"sum": 5
}
}
}
How do I get only the root name i.e 'Records123' in this case for Json (using Json.net or any method) , the way we have XDocument.Root.Name.LocalName in XML...
How to get the Root attributes i.e 'count' in this case like we have XDocument.Root.Attributes() in XML?
You could use JObject like this
var jsonObject = JObject.Parse(jsonString);
foreach (var tmp in jsonObject)
{
Console.WriteLine(tmp.Key);
}
For your sample JSON this should give you Records123 on the console. You have to add some logic here to get the first item only, which is a bit more tricky to JProperty handling.
Edit
For getting the other properties use
var jsonObject = JObject.Parse(jsonString);
foreach(JObject jsonProperty in jsonObject.Children<JProperty>().First())
{
foreach (var property in jsonProperty.Properties())
{
Console.WriteLine(property.Name);
}
}

How to get the name of a JSON object using? (C# Newtonsoft.JSON)

For those of you familiar with Minecraft, the 1.8 update stores the sounds as a file with an encrypted hash as the name (which you can really just change the extension to .ogg to play). There is an index stored as a JSON file in the assets folder which shows the proper sound name for each file with the encrypted hash name.
I'm trying to create a program that which the user types the name and it will find the sound(s) that contains that name. The index is stored in this fashion:
{ "objects":{"minecraft/sounds/mob/wither/idle2.ogg": {
"hash": "6b2f86a35a3cd88320b55c029d77659915f83239",
"size": 19332
},
"minecraft/lang/fil_PH.lang": {
"hash": "e2c8f26c91005a795c08344d601b10c84936e89d",
"size": 74035
},
"minecraft/sounds/note/snare.ogg": {
"hash": "6967f0af60f480e81d32f1f8e5f88ccafec3a40c",
"size": 3969
},
"minecraft/sounds/mob/villager/idle1.ogg": {
"hash": "a772db3c8ac37dfeb3a761854fb96297257930ab",
"size": 8605
},
"minecraft/sounds/mob/wither/hurt3.ogg": {
"hash": "a4cf4ebe4c475cd6a4852d6b4228a4b64cf5cb00",
"size": 16731
}
For example if the user types wither, it will grab the hashes for "minecraft/sounds/mob/wither/idle2.ogg"
and
"minecraft/sounds/mob/wither/hurt3.ogg"
My question is, how do I get the object names (the names, not the properties) to compare with the user's keyword string.
Sorry if I didn't use proper terminology for some words, I don't tinker with JSON files much. Correct my terminology as needed.
EDIT
This answer solves it a lot more nicely (without dynamic):
https://stackoverflow.com/a/32129497/563532
Original answer:
This works:
var obj = JsonConvert.DeserializeObject<dynamic>(#"{ ""objects"":{""minecraft/sounds/mob/wither/idle2.ogg"": {
""hash"": ""6b2f86a35a3cd88320b55c029d77659915f83239"",
""size"": 19332
},
""minecraft/lang/fil_PH.lang"": {
""hash"": ""e2c8f26c91005a795c08344d601b10c84936e89d"",
""size"": 74035
},
""minecraft/sounds/note/snare.ogg"": {
""hash"": ""6967f0af60f480e81d32f1f8e5f88ccafec3a40c"",
""size"": 3969
},
""minecraft/sounds/mob/villager/idle1.ogg"": {
""hash"": ""a772db3c8ac37dfeb3a761854fb96297257930ab"",
""size"": 8605
},
""minecraft/sounds/mob/wither/hurt3.ogg"": {
""hash"": ""a4cf4ebe4c475cd6a4852d6b4228a4b64cf5cb00"",
""size"": 16731
}
}
}");
var t = obj.objects;
var names = new HashSet<String>();
foreach(JProperty fileThing in t)
{
names.Add(fileThing.Name);
}
names.Dump();
Gives:
minecraft/sounds/mob/wither/idle2.ogg
minecraft/lang/fil_PH.lang
minecraft/sounds/note/snare.ogg
minecraft/sounds/mob/villager/idle1.ogg
minecraft/sounds/mob/wither/hurt3.ogg
You can also do this:
var t = obj.objects;
var names = new Dictionary<String, String>();
foreach(JProperty fileThing in t)
{
names.Add(fileThing.Name, (string)t[fileThing.Name].hash);
}
Which gives you a dictionary linking the original name to the hash:
minecraft/sounds/mob/wither/idle2.ogg -> 6b2f86a35a3cd88320b55c029d77659915f83239
minecraft/lang/fil_PH.lang -> e2c8f26c91005a795c08344d601b10c84936e89d
minecraft/sounds/note/snare.ogg -> 6967f0af60f480e81d32f1f8e5f88ccafec3a40c
minecraft/sounds/mob/villager/idle1.ogg -> a772db3c8ac37dfeb3a761854fb96297257930ab
minecraft/sounds/mob/wither/hurt3.ogg -> a4cf4ebe4c475cd6a4852d6b4228a4b64cf5cb00
Assuming you have a jsonString as a string variable.
jsonString = "";
JArray array = JArray.Parse(json);
foreach (JObject content in array.Children<JObject>())
{
foreach (JProperty prop in content.Properties())
{
Console.WriteLine(prop.Name);
}
}

How to get the key of a deserialized json with JSON.Net

I have a json like this
e.result = {
5474: {
name: "john",
last: "doe"
},
8471: {...},
...
}
I get the data this way
JObject o = JObject.Parse(e.Result);
foreach (JToken token in o)
{
Message.show((string)token.First["name"]);
}
That work's fine, but i need to get the key in each iteration. Need to get the 5474 and 8471 values in this example.
Any idea?
((JProperty)token).Name.ToString()

Categories