I'm trying to update the value of JToken but its reference is not getting updated.
JSON string:
{
"Title": "master",
"Presentation": [
{
"Component": {
"Content": {
"Title": "Set New Title",
}
}
}
]
}
and the usage is given below
JObject jo = JObject.Parse(File.ReadAllText(file.json));
foreach (var token in jo.SelectTokens("$..Component.Content").Children())
{
JProperty prop = token.ToObject<JProperty>();
prop.Value = "New Title";
}
string jsonText = JsonConvert.SerializeObject(jo, Formatting.Indented);
In this example, I'm trying to update the value of Title property. It is getting updated within foreach, means local variable is getting updated but changes are not reflecting in main jobject.
Can anyone help me if i'm doing anything wrong?
Once you call ToObject then you are working with a copy.
If instead you try this, it should work:
JObject jo = JObject.Parse(File.ReadAllText(file.json));
foreach (var prop in jo.SelectTokens("$..Component.Content")
.Children().OfType<JProperty>())
{
prop.Value = "New Title";
}
string jsonText = JsonConvert.SerializeObject(jo, Formatting.Indented);
or to handle multiple types of JTokens:
JObject jo = JObject.Parse(File.ReadAllText(file.json));
foreach (var token in jo.SelectTokens("$..Component.Content")
.Children())
{
var prop = token as JProperty;
if (prop != null) prop.Value = "New Title";
var array = token as JArray;
if (array != null)
{
// some other logic
}
}
string jsonText = JsonConvert.SerializeObject(jo, Formatting.Indented);
The answer from Stuart may be erroneous because "Content" may contain other children and all of theme could be renamed or their values could be changed.
I've encountered the similar issue.
From the body I needed to remove value, because it was too long for logging and unnecesary, so I needed to change it's value.
I could've changed it with indexer like token["name"], but "name" could be of different cases, so I needed an universal case independent way to erase it's value:
And I implemented it other way:
var jObject = JObject.Parse(body);
JToken token;
if (jObject.TryGetValue(
Constants.FieldName,
StringComparison.InvariantCultureIgnoreCase,
out token))
{
var jProperty = token.Parent as JProperty;
if (jProperty != null)
{
jProperty.Value = "removed";
}
body = jObject.ToString(Formatting.Indented);
}
Here you have a magnificient example of how you can do this, in a proper way. Both solutions above didn't work for me, but this very simple yes. Simply work with the JToken or Object as an array. That's all.
https://www.newtonsoft.com/json/help/html/ModifyJson.htm
Related
I get a json string in a function that string could be json object or List of json objects i.e [{"user": "123", "password": "abc", "class":"A"}].
I want to check if this Json string contains a Property user and password then update their value.
So, I get the string and convert it into JToken by using
var jToken = JToken.Parse(result);
if (jToken is JArray)
convert into JArray
else
convert into JObject
After that I have to check that above keys exist in JArray or JObject.
Note I want to check the case insensitivity of keys too.
Can someone help how to check case insensitivity of keys in Json Array and object and modify their values .
You can perform case-insensitive property lookups via JObject.Property().
var json = "[{ 'user':'123','password':'abc','class':'A' }]";
var token = JToken.Parse(json);
foreach (JObject user in token as JArray)
{
var userProp = user.Property("USER", StringComparison.OrdinalIgnoreCase);
if (userProp != null)
{
userProp.Value = "updated username";
}
var passwordProp = user.Property("PaSsWoRd", StringComparison.OrdinalIgnoreCase);
if (passwordProp != null)
{
passwordProp.Value = "updated password";
}
}
Console.WriteLine(token.ToString());
This results in the following json:
[
{
"user": "updated username",
"password": "updated password",
"class": "A"
}
]
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}");
}
}
}
I am trying to implement a dynamic condition on a JSON Object.
After searching for a while, I am not able to find any resources which can meet my needs.
In the below fashion, I am getting the JsonObject dynamic string into jsonObject variable.
string inputFromAPI = client.GetStringAsync(URL).Result;
dynamic jsonObject = JValue.Parse(inputFromAPI);
I now have a condition which can change on need basis.For example I can have a condition which says
"inputFromAPI.DidWeCharge == true && inputFromAPI.DidWeHold == false"
The above line can change on the fly. Any inputs how to address this will be greatly appreciated.
I can't comment for clarification (don't have the rep yet), but if you need to be able to read the property name because it's changing you can do this. You would have to know the name though.
var JSONobj = JObject.Parse(json);
foreach (JToken child in JSONobj.Children())
{
var prop = child as JProperty;
var propertyName = prop.Name; // this will give you the name of the property
if (propertyName == "DidWeCharge")
{
var value = prop.Value; // Do something here with value?
}
if (propertyName == "DidWeHold")
{
var value = prop.Value; // Do something here with value?
}
var propertyType = prop.Value.Type; // this return the type as a JTokenType enum.
}
I don't know how nested your JSON is, so you may have to traverse further down with another foreach on the child by doing child.Children().
You can use ExpandoObject:
var expandoObj = JsonConvert.DeserializeObject<ExpandoObject>(jsonObject);
expandoObj.yourProperty
JsonConvert is from Newtonsoft.Json package.
You may be able to use Jpath:
using Newtonsoft.Json -
....
var json = #"
{
stuff : [
{
value : 1
},
{
value : 2
}
]
}";
var token = JToken.Parse(json);
var something = token.SelectTokens("$.stuff[?(#.value == 1)]").ToList();
I want to parse following string , bellow is my code , and below is my string
string jsn = Convert.ToString(
#"{
'TaxProfile':{'id':258658,'IncomeTypeStatus':[{'IncomeType':'0001','StatusCodeDesc':'Ready For SAP','StatusCode':'RFS','PayFromCountryCode':'IE'}],'ExpirationDate':null,'FormName':null},
'ErrorJSON':'[{\'TypeID\':\'Z_FI_MDG\',\'SeverityCode\':\'3\',\'Note\':\'\\\'An Electronic Fund Transactions (EFT) routing number is comprised of a three-digit financial institution number and a five-digit branch number, preceded by a \\\\\\\'leading zero\\\\\\\'. \\\\\\\\r\\\\\\\\n•YYY: Institution\'}]'
}"
);
JObject jo = JObject.Parse(jsn);
// dynamic jo = JObject.Parse(jsn);
TenantPayeeMessage apTenantMessage = null;
// JObject jo = o;
// var auditObject = jo.ToString();
JToken PartnerReferenceId;
string Payeeid, PayeeStatus, bpid = string.Empty;
JToken[] items = null;
JToken sectionStatus = null;
JToken TaxIncomType = null;
JToken[] bank = null;
var bankJson = new Dictionary<string, string>();
JToken ErrorJSONSeverityNote,
ErrorJSONSeverityCode,
ErrorJSONTypID,
BasicErrorJSON,
Basicbpid,
Basicstatus,
BasicId, CompliancebpErrorJSON,
Compliancebpid, Compliancestatus, ComplianceId, ErrorJSONpp,
bbpidpp, statuspp,
PaymentProfileId, FormName,
ExpirationDate,
PayFromCountryCode, StatusCode, StatusCodeDesc, IncomeType, TaxProfileId;
//Guid SyncIdentifier = Guid.Parse(jo["BusinessPartnerSUITEBulkReplicateConfirmation"]["BusinessPartnerSUITEReplicateConfirmationMessage"]["MessageHeader"]["UUID"].Value<string>());
if (null != jo["TaxProfile"]["id"] && null != jo["TaxProfile"]["id"])
{
TaxProfileId = jo["TaxProfile"]["id"].Value<string>();
}
TaxIncomType = jo["TaxProfile"]["id"]["IncomeTypeStatus"].Value<string>();
in last line i get error
Cannot access child value on Newtonsoft.Json.Linq.JValue.
I am not sure where i am going wrong i want to parse above string
Your code looks like (I've removed code not related to exception and formatted JSON string):
var jsn = Convert.ToString(
#"{
'TaxProfile': {
'id': 258658,
'IncomeTypeStatus': [
{
'IncomeType': '0001',
'StatusCodeDesc': 'Ready For SAP',
'StatusCode': 'RFS',
'PayFromCountryCode': 'IE'
}
],
'ExpirationDate': null,
'FormName': null
},
'ErrorJSON': '[{\'TypeID\':\'Z_FI_MDG\',\'SeverityCode\':\'3\',\'Note\':\'\\\'An Electronic Fund Transactions (EFT) routing number is comprised of a three-digit financial institution number and a five-digit branch number, preceded by a \\\\\\\'leading zero\\\\\\\'. \\\\\\\\r\\\\\\\\n•YYY: Institution\'}]'
}");
var jo = JObject.Parse(jsn);
var TaxIncomType = jo["TaxProfile"]["id"]["IncomeTypeStatus"].Value<string>();
Code
jo["TaxProfile"]["id"]
returns 258658. So, if you try to get IncomeTypeStatus property of it, you'll get above mentioned exception. Probably you need to remove id from your call chain.
jo["TaxProfile"]["IncomeTypeStatus"]
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);