C# Unable to modify Json with Newtonsoft - c#

I have a string type variable named final and it contains the following Json:
{
"Game": {
"Player_Decks": {
"1": {
"Card_List": "2_Yellow,1_Blue,Reverse_Green,5_Yellow,5_Red,7_Red,2_Blue",
"Card_Count": 7
},
"2": {
"Card_List": "5_Blue,9_Green,4_Yellow,6_Green,0_Red,2_Green,6_Yellow",
"Card_Count": 7
}
},
"Deck_NoCards": {}
}
}
My code looks like this: (taken from here: https://www.newtonsoft.com/json/help/html/ModifyJson.htm)
JObject rss = JObject.Parse(final);
JObject channel = (JObject)rss["Game.Player_Decks.1"];
channel.Property("Card_Count").AddAfterSelf(new JProperty("new", "New value"));
I want to add another value after Card_Count, but I have a feeling that my string isn't "compatible" or something. What can be done here to fix my problem?

Reposting comment as answer here:
You cannot access the nested object using a dotted path "Game.Player_Decks.1". Instead you need to individually address each property within each object.
JObjects are effectively an array of named properties, JObject implements IDictionary<string, JToken?> so as long as each child element is also a JObject then you can use the string index to reference the element in the next level.
JObject game = (JObject)rss["Game"];
JObject decks = (JObject)game["Player_Decks"];
JObject channel = (JObject)decks["1"];
channel.Property("Card_Count").AddAfterSelf(new JProperty("new", "New value"));
The following syntax should also work:
JObject channel = rss["Game"]["Player_Decks"]["1"] as JObject;
Also, have you considered using a Json Array instead of properties named 1, 2, etc. like so:
{
"Game": {
"Player_Decks": [
{
"Card_List": "2_Yellow,1_Blue,Reverse_Green,5_Yellow,5_Red,7_Red,2_Blue",
"Card_Count": 7
},
{
"Card_List": "5_Blue,9_Green,4_Yellow,6_Green,0_Red,2_Green,6_Yellow",
"Card_Count": 7
}
],
"Deck_NoCards": {}
}
}
and accessed as:
JObject rss = JObject.Parse(final);
JObject game = (JObject)rss["Game"];
JArray decks = (JArray)game["Player_Decks"];
JObject deck1 = (JObject)decks[0];

Related

I can´t find the track and trace number in my json string

I can´t find a value in a json string using json.net
I´ve tried jsonstr[0].track_numbers[0].track_number
This is my json file.
{
"0": {
"increment_id": "112",
"track_numbers": [
{
"track_number": "2223",
"title": "tit",
"carrier_code": "custom"
}
]
},
"live_shipping_status": "Delivered"
}
I want to find the Track_nummber.
dynamic jsonstr = JsonConvert.DeserializeObject(json));
var track = jsonstr[0].track_numbers[0].track_number
(donsent work)
The 0 of your json is a string key, not an index position:
dynamic obj = JsonConvert.DeserializeObject(json);
var trackNumber = obj["0"].track_numbers[0].track_number;
Note the difference in getting the first entry of track_numbers, which is an array.

Error when trying to extract values from a Json Object C#

I have a Json string like below and this is only a small snippet. The number in quotation marks is a Unix Time which i will need to use to iterate over each object.
{
"result": {
"1534860000": [
"1534860000",
19,
41
],
"1534863600": [
"1534863600",
11,
16
],
"1534867200": [
"1534867200",
2,
5
]
}
}
But when I attempt to extract the data in the arrays I get an error:
System.InvalidOperationException: 'Cannot access child value on Newtonsoft.Json.Linq.JProperty.'
Code:
JObject jsonObj = JObject.Parse(response);
string unixTime = Helpers.ConvertToUnix(yesterday.AddHours(hour)).ToString();
foreach (var obj in jsonObj["result"])
{
var array = obj[unixTime]; //here is where the error occurs
}
Anyone able to shed some light on what I am missing?
If we simplify your example code a little to remove the unixTime element (let's just hardcode it for now), we end up with this:
JObject jsonObj = JObject.Parse(response);
string unixTime = "1534860000";
At this stage, we have jsonObj which refers to the root of the JSON object and has a single property of result. Repeating your foreach here for context:
foreach (var obj in jsonObj["result"])
{
var array = obj[unixTime]; //here is where the error occurs
}
You end up with obj referring to the JSON path of result.1534860000. The problem is you're then looking for a property 1534860000 at this JSON path (result.1534860000.1534860000), which does not exist.
You can just get the value directly, like so:
var array = obj["result"][unixTime]
Of course, this requires some error-checking for ensuring the path exists, etc, but it demonstrates the point.
After some help from Kirk Larkin I thought I would post a code snippet up.
JObject jsonObj = JObject.Parse(response);
int hour = 0;
string unixTime = Helpers.ConvertToUnix(yesterday.AddHours(hour)).ToString();
var array = jsonObj["result"][unixTime];
It now returns the contents of the array.

Replace a JSON value of a property in several JObjects

I have a JSON file I'm reading from text and parsing it into JObject using Newtonsoft.Json.Linq. The JSON file looks like this:
{
"EntityTypeDto":[
{
"EntityType":"Grade",
"Language":"ES"
},
{
"EntityType":"ApplicationType",
"Language":"ES"
},
{
"EntityType":"Borough",
"Language":"ES"
}
]
}
Using the Newtonsoft library, are there any methods I can leverage on JObject to replace the Language property of all the objects to another value? If not what would be another way to do this? This project is a console application in C#, VS 2012, thanks.
You don't need Linq here to achieve what you need , Linq is for consult data, not for modify it. So you can just, eg, a foreach to iterate and modify the elements of the array:
JObject json= JObject.Parse(jsonString);
JArray entityTypeDtos= (JArray)json["EntityTypeDto"];
foreach(var e in entityTypeDtos)
{
if(e["Language"] != null)
e["Language"]="EN";
}
I'm guessing by the Linq tag you would like a Linq approach try this
string json = #"{
'EntityTypeDto':[
{
'EntityType':'Grade',
'Language':'ES'
},
{
'EntityType':'ApplicationType',
'Language':'ES'
},
{
'EntityType':'Borough',
'Language':'ES'
}
]
}";
JObject myjobj = JObject.Parse(json);
JArray EntityType = (JArray)myjobj["EntityTypeDto"];
(from eobj in EntityType
where eobj["Language"]="ES"
select eobj).ForEach(x => x["Language"]="New Value");

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

How do I get the value in a generic Dictionary?

I have a json string like this:
{
"ipaddress": "xxx",
"hostname": "comcast.xxx",
"popup": {
"position": "1256",
"pagename": "home"
}
}
In my Windows Form code I've been using JavaScriptSerializer for phare those line to dictionary.
var obj = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
It is working fine at the moment, but I don't know how to get value inside popup? Because it's another dictionary.
[7] = {[popup, System.Collections.Generic.Dictionary`2[System.String,System.Object]]}
The fastest (yet unsafe) way of doing it is like this is via the indexer:
First extract the first dictionary and cast, since the first dictionary will yield an object of type object:
var popup = (Dictionary<string, object>)obj["popup"];
Then, you extract the values based on keys:
var position = popup["position"];
var pagename = popup["pagename"];
If you're not sure both keys will exist in the result, you can use Dictionary.TryGetValue if they exist:
obj position;
if (!popup.TryGetValue("position", out position))
{
// Key isn't in the dictionary.
}
Use JSON .Net, then simply:
JObject dynJson = JObject.Parse(jsonString);
followed by:
string data = dynJson["popup"]["position"];
JObject.Parse

Categories