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

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()

Related

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);
}
}

Removing an element from a JSON response

I have a JSON string from which I want to be able to delete some data.
Below is the JSON response:
{
"ResponseType": "VirtualBill",
"Response": {
"BillHeader": {
"BillId": "7134",
"DocumentId": "MN003_0522060",
"ConversionValue": "1.0000",
"BillType": "Vndr-Actual",
"AccountDescription": "0522060MMMDDYY",
"AccountLastChangeDate": "06/07/2016"
}
},
"Error": null
}
From above JSON response I want to able remove the
"ResponseType": "VirtualBill", part such that it looks like this:
{
"Response": {
"BillHeader": {
"BillId": "7134",
"DocumentId": "MN003_0522060",
"ConversionValue": "1.0000",
"BillType": "Vndr-Actual",
"AccountDescription": "0522060MMMDDYY",
"AccountLastChangeDate": "06/07/2016"
}
},
"Error": null
}
Is there an easy way to do this in C#?
Using Json.Net, you can remove the unwanted property like this:
JObject jo = JObject.Parse(json);
jo.Property("ResponseType").Remove();
json = jo.ToString();
Fiddle: https://dotnetfiddle.net/BgMQAE
If the property you want to remove is nested inside another object, then you just need to navigate to that object using SelectToken and then Remove the unwanted property from there.
For example, let's say that you wanted to remove the ConversionValue property, which is nested inside BillHeader, which is itself nested inside Response. You can do it like this:
JObject jo = JObject.Parse(json);
JObject header = (JObject)jo.SelectToken("Response.BillHeader");
header.Property("ConversionValue").Remove();
json = jo.ToString();
Fiddle: https://dotnetfiddle.net/hTlbrt
Convert it to a JsonObject, remove the key, and convert it back to string.
Sample sample= new Sample();
var properties=sample.GetType().GetProperties().Where(x=>x.Name!="ResponseType");
var response = new Dictionary<string,object>() ;
foreach(var prop in properties)
{
var propname = prop.Name;
response[propname] = prop.GetValue(sample); ;
}
var response= Newtonsoft.Json.JsonConvert.SerializeObject(response);

Retrieve boolean value from json data containing string key/values

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.

How to read property names in array from json string?

Here is the list of data I receive, property names are can be different;
{"data":"[
{
"id":"1",
"name":"aa",
"email":"aa#aa.com",
"address":"11"
},
{
"id":"2",
"name":"bb",
"email":"bb#bb.com",
"address":"22"
}
]"}
Here is my c# code
Which I get an error on the 3rd line. Unable to read json data. Check the url you typed.Invalid cast from 'System.String' to 'Newtonsoft.Json.Linq.JObject'.
var jsonStr = wc.DownloadString(url);
JToken outer = JToken.Parse(jsonStr);
JObject inner = outer["data"].Value<JObject>();
List<string> keys = inner.Properties().Select(p => p.Name).ToList();
How can my output be like this;
id
name
emal
address
It would be great if I also consider n level array such as address > street and address > postcode
Many thanks.
var jObj = JObject.Parse(json);
var props = jObj["data"][0].Select(x => ((JProperty)x).Name).ToList();
BTW: your json is not correct, it should be something like this
{data:[
{ "id":"1",
"name":"aa",
"email":"aa#aa.com",
"address":"11"
},
{"id":"2",
"name":"bb",
"email":"bb#bb.com",
"address":"22"
}
]}
See the " after data: in your question

Categories