Cannot access a jObject token in c# - c#

I have the following json called 'originalJson'
{
"user_active": true,
"user_firstname": "Bob",
"user_lastname": "Tester",
"user_displayname": "Bobby",
"user_primary_email": "bob#tester.com",
"user_login_enabled": true,
"user_profile": {
"user_locale": "en-gb",
"user_lang": "en-gb"
},
"user_identities": [],
"user_roles": [
{
"app_id": "74a019c9-7171-4af0-a773-3984edaa35ca",
"context_uuid": "74a019c9-7171-4af0-a773-3984edaa35ca",
"context_type": "context_application",
"role_oid": "test_role_a",
"role_start_date": "2020-06-27T13:00:00Z",
"role_end_date": "2021-06-27T13:00:00Z"
}
]
}
and I am trying to replace the role_start_date and role_end_date values.
I have tried the following
JObject jObj = JObject.Parse(originalJson);
jObj["user_roles"]["role_start_date"] = somenewstartDate;
jObj["user_roles"]["role_end_date"] = somenewendDate;
However it is failing and doesn't like the "jObj["user_roles"]["role_start_date"]". I thought it would be pretty simple to do, I must be missing something.
Any ideas?

The property "user_roles" is an array of objects not a single object. You are trying to set a property value in the first entry in that array, so you need to do:
jObj["user_roles"][0]["role_start_date"] = somenewstartDate;
jObj["user_roles"][0]["role_end_date"] = somenewendDate;

Related

How to check for a key/node existence in JSON c#?

My Json looks like below.
I want to check if the following key/nodes exist or not in the below Json.
1st node-> AutomationFramework.Technique.Available
2nd node->Verify.Customer
{
"$type": "Config",
"Available": true,
"Verify": {
"$type": "UserList`2"
"Customer":"Peter"
},
"Identification": true,
"Verification": false,
"AutomationFramework": [
{
"$type": "custom",
"Name": "ATL",
"Technique": {
"$type": "Technique",
"PropertyName": "Name",
"Available": true
},
"SolveTechnique": {
"$type": "Userdefined",
"Available": true
},
"AITechnique": {
"$type": "AI",
"X_Value": 2,
"Y_Value": 3,
"Available": true
},
"WaitTechnique": {
"$type": "Recurssion",
"Available": true
}
}
]
}
I tried with the following code (ParseJson below is a method to parse JSON which I have created):
JObject obj = JObject.Parse(ParseJson(#"C:\Test\Test.Config"));
IEnumerable<JToken> token = obj.SelectTokens("AutomationFramework.Technique.Available", errorWhenNoMatch: false);
Here it is returning null even if the node is present.
I want a generic method that could handle all scenarios. Any help will be appreciated.
The method should return True/False based on the existence.
Your code is not working because AutomationFramework is a list, not an object.
Also, be sure to cast the result to an appropriate type. If you know the type of the token, you can cast directly in place. If you don't know the type at compile time, you can store in a JToken variable instead.
In your code you are using SelectTokens. But if you are expecting only one of that token, you should use SelectToken instead.
Assuming that the desired node Technique will always be present in the first item of the AutomationFramework list, you could do:
JObject obj = JObject.Parse(ParseJson(#"C:\Test\Test.Config"));
bool avail = (bool)obj.SelectToken("AutomationFramework[0].Technique.Available", errorWhenNoMatch: false);
string cust = (string)obj.SelectToken("Verify.Customer", errorWhenNoMatch: false);

C# - parse JSON with dynamic and access property name with colon

When getting a JSON with property with :
i.e.
{
"root": {
"sim:names": [{
"name": "Tom"
},
{
"name": "David"
}]
}
}
I'm using Newtonsoft Dynamic parse.
var data = JsonConvert.DeserializeObject<dynamic>(jsonString);
I'm trying to access
data.root.sim:names
But getting compilation error "Invalid expression term ':'"
How can I access it?
You should convert it to object
var data = JsonConvert.DeserializeObject<Object>(jsonString);
And access it like this:
var value = ((JObject)data)["root"]["sim:names"];

Capture json data from Steam API

So I what I am trying to do is capture/extract specific data from Steams API for dota2 heroes. I am using C# to do this with this method.
https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=2D13D618DA712015812E970165632F02&language=en_us
{
"result": {
"heroes": [
{
"name": "npc_dota_hero_antimage",
"id": 1,
"localized_name": "Anti-Mage"
},
]
}
This is the code I have been trying with:
WebClient c = new WebClient();
var data = c.DownloadString("https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=2D13D618DA712015812E970165632F02&language=en_us");
JObject o = JObject.Parse(data);
string heroname = (string)o["name"];
But it only returns an error saying the value of "heroname" is null.
Any ideas?
o is going to be an object that contains one key: result. o["result"] will in turn contain a key called heroes. o["result"]["heroes"] is an array of objects. So o["result"]["heroes"][0] will be the first item, and o["result"]["heroes"][0]["name"] is the name from the first item.

How to get values from a Json in jquery, set text values?

I have a data table witch i serialize into a json and then parse to my view code where i use J Query to get those values.
When i use
document.getElementById('Name').value = UserInfo.Name;
the
Userinfo.Name = null,
what am i doing wrong for not being able to read my UserInfo.
Could someone please tell me how i can get the values out of UserInfo.
Below is all my code:
C# Code:
public JsonResult SearchForUser(int id)
{
string Sjson = JsonConvert.SerializeObject(DataTable, Formatting.Indented);
return Json(Sjson, JsonRequestBehavior.AllowGet);
}
J Query code:
$.post("SearchForUser", { id: id }, function (UserInfo) {
if (UserInfo != "")
{
document.getElementById('Name').value = UserInfo.Name;
document.getElementById('Surname').value = UserInfo.Surname;
}
});
Json :
"[ {
"UserId": 5,
"UserName": "JamesBond#MI6.com",
"UserPassword": "007",
"Name": "James",
"RoleId": 2,
"EmployeeId": 5,
"Active": true,
"Name1": "James",
"Surname": "Bond",
"IdNumber": "007",
"PassportNumber": "700",
"PhysicalAddress": "MI6",
"PostalAddress": "MI7",
"TelNumber": "0126659007",
"SelNumber": "0837777007",
"EmailAddress": "JamesBond#MI6.com",
"Designation": "Spy",
"DateEmployedFrom": "2013-06-19T00:00:00",
"Active1": true } ]"
Extra:
I am working with MVC razor.
Thanks in advance.
Edit still can't access values (This edits are in reply with answers)
It looks like your JSON object is an array with one item. In that case you should be accessing UserInfo[0].Name. Also verify that document.getElementById('Name') does indeed find an element.
Also, since you're using jQuery, document.getElementById('Name') = UserInfo[0].Name could be rewritten as $('#Name').val(UserInfo[0].Name).
Use var info=jQuery.parseJSON(UserInfo); to parse the value and then info.Name will give you result
DEMO
Like your JSON object structure Check here

Create javascript object which will convert to JSON then to Dictionary<string, bool>

I have a C# class which contains a property of Dictionary
I have a web-page which contains a list of items i need to cast into this dictionary.
My web-site will send the list up to my C# MVC application as JSON and then JsonConvert.Deserialise the JSON into my Dictionary object.
JsonConvert.Deserialise is expecting JSON in the following format:
"MyVariableName":{
"Item 1":true,
"Item 2":true
}
I need to know how i can construct this object in JavaScript.
So far, i have tried this without luck:
var items = [];
var v = $('#Items :input');
$.each(v, function(key, val) {
items.push({
key: val.value,
value: val.checked
});
});
JSON.stringify(v, null, 2);
But this returns a json converted value of:
"MyVariableName": [
{
"key": "Item 1",
"value": true
},
{
"key": "Item 2",
"value": true
}]
Which in turn does not de-serialize to my dictionary.
Thanks
Don't make an array; make an object:
var items = {};
$('#Items :input').each(function(i, val) {
items[val.value] = val.checked;
});
You have to use javascript serialization
One more thing you have different value int key, value pair like string and Boolean type, so you have to use Dictionary type.
And JavaScriptSerializerobject you will get System.Web.Script.Serialization name space of System.Web.Extensions.dll, v4.0.30319 assembly.
var jSerializer = new JavaScriptSerializer();
var newList= jSerializer.Deserialize<Dictionary<string,object>>(newData);

Categories

Resources