Fetch Value from Json without DeserializeObject C# - c#

Following Json is return from API call.
{
"version": "dddf2222",
"data": {
"account": {
"username": "34343",
},
},
"error": 0
}
I want to fetch value of username without DeserializeObject.

dynamic stuff = JsonConvert.DeserializeObject(myJson);
Console.WriteLine(stuff.data.account.username);
using using Newtonsoft.Json.Linq
dynamic stuff = JObject.Parse(myJson);
Console.WriteLine(stuff.data.account.username);

Related

How do you deserialize a JSON to get a string value without having to build an entire model? Below is example code I included

Example JSON, for example say I want the quote and author values. I wasn't able to get them unless I built a model around the JSON, which I'm not wanted to do as it would be more time consuming.
{
"success": {
"total": 1
},
"contents": {
"quotes": [
{
"quote": "Plant your own garden and decorate your own soul, instead of waiting for someone to bring you flowers.",
"length": "102",
"author": "Veronica A. Shoffstall",
"tags": [
"flowers",
"inspire",
"self-help",
"soul"
],
"category": "inspire",
"language": "en",
"date": "2022-12-22",
"permalink": "https://theysaidso.com/quote/veronica-a-shoffstall-plant-your-own-garden-and-decorate-your-own-soul-instead-o",
"id": "LQbKQGxVA2rcH4lIwn6OIweF",
"background": "https://theysaidso.com/img/qod/qod-inspire.jpg",
"title": "Inspiring Quote of the day"
}
]
},
"baseurl": "https://theysaidso.com",
"copyright": {
"year": 2024,
"url": "https://theysaidso.com"
}
}
My test example code with URL below. I tried it with Dynamic Object but can never get to the string.
try
{
private static readonly HttpClient _httpClient = new HttpClient();
// Make the API request
var response = _httpClient.GetAsync("https://quotes.rest/qod?language=en").Result;
response.EnsureSuccessStatusCode();
// Do something with the response
var value11 = response.Content.ReadAsStringAsync().Result;
var gett = JsonConvert.DeserializeObject<dynamic>(value11);
var quote= gett.contents.quotes.quote;
return quote;
}
catch (Exception ex)
{
quote = ex.Message;
return quote;
}
Looking at the JSON structure the quotes property is an array and as such you should use
var quote = gett.contents.quotes[0].quote;
Assuming that deserialization was not the cause of the failure.
There is no json convert error. quotes is array you can access gett .contents.quotes[0].quote.
Tips; you don't need to json convert and ReadAsString you can easily use like response.Content.ReadFromJsonAsync().Result?.contents.quotes[0].quote

Get Value From JSON File stored in Azure Storage Using C#

I have JSON file in Azure Storage which I am reading using C#. In that JSON file there is anode called SQLViewDifinition and that node I have SQL which I need to fetch.
I have read the file into a string and converted that string in JObject. I have the JSON now but is finding it difficult to read that particular node. Tried with JToken and Jproperty. But could not crack it.
JSON file looks like this:
{
"jsonSchemaSemanticVersion": "1.4.0",
"imports": [
{
"corpusPath": "cdm:/foundations.cdm.json"
},
{
"corpusPath": "localCdm:/foundations.cdm.json"
}
],
"definitions": [
{
"entityName": "METCredManCollectionGroupEntity",
"exhibitsTraits": [
{
"traitReference": "is.CDM.entityVersion",
"arguments": [
{
"name": "versionNumber",
"value": "1.0.0"
}
]
},
{
"traitReference": "has.sqlViewDefinition",
"arguments": [
{
"name": "sqlViewDefinition",
"value": "CREATE VIEW [DBO].[METCREDMANCOLLECTIONGROUPENTITY] AS SELECT T1.COLLECTIONGROUPID AS COLLECTIONGROUPID, T1.DESCRIPTION AS DESCRIPTION, T1.RECID AS CREDMANCOLLECTIONGROUPTABLERECID, T1.DATAAREAID AS CREDMANCOLLECTIONGROUPTABLEDATAAREAID, T1.RECVERSION AS RECVERSION, T1.PARTITION AS PARTITION, T1.RECID AS RECID FROM CREDMANCOLLECTIONGROUPTABLE T1"
}
]
},
{
"traitReference": "has.backingElements",
"arguments": [
{
"name": "backingElements",
"value": "CredManCollectionGroupTable"
}
]
}
],
"hasAttributes": [
{
"name": "CollectionGroupId",
"dataType": "CredManCollectionGroupId",
"isNullable": true,
"displayName": "Collection group",
"maximumLength": 10
},
{
"name": "Description",
"dataType": "Description",
"isNullable": true,
"displayName": "Description",
"maximumLength": 60
},
{
"name": "CredmanCollectionGroupTableRecId",
"dataType": "other",
"isNullable": true,
"displayName": "Record-ID"
},
{
"name": "CredmanCollectionGroupTableDataAreaId",
"dataType": "other",
"isNullable": true,
"displayName": "Company"
}
],
"displayName": "MET Collection groups (Shared)"
},
{
"explanation": "Collection group",
"dataTypeName": "CredManCollectionGroupId",
"extendsDataType": "SysGroup"
},
{
"explanation": "Group",
"dataTypeName": "SysGroup",
"extendsDataType": "string"
},
{
"explanation": "Description",
"dataTypeName": "Description",
"extendsDataType": "string"
}
]
}
I need to find sqlViewDefinition from this file.
So far I can read the JSON in a JSON object. But could not find a way to get the view definition.
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Nancy.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class FindFiles
{
// Main Method with int return type
static int Main(String[] args)
{
Console.WriteLine("Buid SQL");
// for successful execution of code
return X("FILE_NAME");
}
public static int X(string fileName)
{
//connection string
string storageAccount_connectionString = "CONNECTION_STRING";
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageAccount_connectionString);
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("CONTAINER");
//The specified container does not exist
try
{
//root directory
CloudBlobDirectory dira = container.GetDirectoryReference(string.Empty);
//true for all sub directories else false
var rootDirFolders = dira.ListBlobsSegmentedAsync(true, BlobListingDetails.Metadata, null, null, null, null).Result;
foreach (var blob in rootDirFolders.Results)
{
if (blob.Uri.OriginalString.Contains(fileName, StringComparison.OrdinalIgnoreCase) && blob.Uri.OriginalString.Contains(".cdm.json", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Blob: " + blob.Uri.OriginalString);
if (blob.GetType() == typeof(CloudBlockBlob))
{
CloudBlockBlob b = (CloudBlockBlob)blob;
string jsonText = b.DownloadTextAsync().Result;
Dictionary<string, object> json_Dictionary = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(jsonText.ToString());
JObject json = JObject.Parse(jsonText);
}
}
}
}
catch (Exception e)
{
// Block of code to handle errors
Console.WriteLine("Error", e);
}
return 1;
}
}
As you are using .NET 6 and because the structure is always the same, the easiest way to deserialize is to mimic the structure of the JSON in C# classes. You can then easily deserialize the JSON into objects and access the properties of the objects instead of "brachiating" through dynamic data.
In order to get the classes, you can use Visual Studio's Paste Special function (Edit -> Paste special -> Paste JSON as classes). This generates the classes for you (you can adjust the classes if you don't need parts of them or change the casing of the property names; also you can use attributes to customize the serialization).
Afterwards, it is easy to parse the JSON into an object, e.g. (I've put your sample JSON into the jsonContent variable):
var obj = System.Text.Json.JsonSerializer.Deserialize<Rootobject>(jsonContent);
Because it still is a complex structure, getting to the SQL needs a bit of code:
Console.WriteLine(obj
.definitions[0]
.exhibitsTraits
.Where(x => x.traitReference == "has.sqlViewDefinition")
.First().arguments.Where(x => x.name == "sqlViewDefinition")
.First().value);
Finally, the above code writes the following output:
CREATE VIEW [DBO].[METCREDMANCOLLECTIONGROUPENTITY] AS SELECT T1.COLLECTIONGROUPID AS COLLECTIONGROUPID, T1.DESCRIPTION AS DESCRIPTION, T1.RECID AS CREDMANCOLLECTIONGROUPTABLERECID, T1.DATAAREAID AS CREDMANCOLLECTIONGROUPTABLEDATAAREAID, T1.RECVERSION AS RECVERSION, T1.PARTITION AS PARTITION, T1.RECID AS RECID FROM CREDMANCOLLECTIONGROUPTABLE T1
You can use this documentation to get familiar with JSON handling in .NET 6.

JSON FIle not updating - getting "Cannot perform runtime binding on a null reference" error

Using C#, I am trying to change values in a JSON file however the values are not changing.
Below is the JSON - I intend on changing.
{
"client": {
"name": "ClientName",
"pageTitle": "PageTitle",
"serverId": 234
},
"connection": {
"router": {
"webSocketURL": "wss://pbnasdadasdasd",
"signalRUrl": "https://pbncrasdasdasdasd",
"endPoint": "https://pbncasdasdadasd",
"type": "BabelFish",
"protocol": "WebClientGameplayProtocol.WebClientGameplayProtocolDefinition",
"transport": [
"webSockets"
]
}
}
}
This is what my C# code looks like in the method.
string json = File.ReadAllText(Jsonfile);
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
jsonObj["client"]["serverId"] = "7001";
jsonObj["client"]["connection"]["router"]["webSocketURL"] = "wss://xrouter.program.eu";
jsonObj["client"]["connection"]["router"]["signalRUrl"] = "https://xrouter.program.eu/h";
jsonObj["client"]["connection"]["router"]["endPoint"] = "https://xrouter.program.eu/";
When I run my code I get a 'Cannot perform runtime binding on a null reference" error, and not sure why when there are already values in that area. ****I no longer get this error - My path was incorrect in the jsonObj****
see error below:
Thank you in advance.
The error is due to jsonObj["client"]["connection"].. where ["client"] doesnt exist for connection properties. also try using JObject.Parse
string json = File.ReadAllText(Jsonfile);
var jsonObj = JObject.Parse(json);
jsonObj["client"]["serverId"] = "7001";
jsonObj["connection"]["router"]["webSocketURL"] = "wss://xrouter.program.eu";
jsonObj["connection"]["router"]["signalRUrl"] = "https://xrouter.program.eu/h";
jsonObj["connection"]["router"]["endPoint"] = "https://xrouter.program.eu/";
Console.WriteLine(jsonObj.ToString());
Output
{
"client": {
"name": "ClientName",
"pageTitle": "PageTitle",
"serverId": "7001"
},
"connection": {
"router": {
"webSocketURL": "wss://xrouter.program.eu",
"signalRUrl": "https://xrouter.program.eu/h",
"endPoint": "https://xrouter.program.eu/",
"type": "BabelFish",
"protocol": "WebClientGameplayProtocol.WebClientGameplayProtocolDefinition",
"transport": [
"webSockets"
]
}
}
}
Based on your json hierarchy, for you to update websocket url, you need to use the below line of code to update the attribute value
jsonObj["connection"]["router"]["webSocketURL"] = "wss://xrouter.program.eu";

Reading a json file and change it with JSON.NET

JSON is really new to me. How can i use JSON.NET to add a key value pair into a already created json file?
It looks like this:
{
"data": {
"subData1": {
"key1":"value1",
"key2":"value2",
"key3":"value3"
},
"subdata2": {
"key4":"value4",
"key5":"value5",
"key6":"value6"
}
}
"key7":"value7",
"key8":"value8"
}
Say for an example that i want to change it to the following:
{
"data": {
"subData1": {
"key1":"value1",
"key2":"value2",
"key3":"value3"
},
"subdata2": {
"key4":"value4",
"key5":"value5",
"key6":"value6"
},
"newSubData": {
"myKey1":"myVal1",
"myKey2":"myVal2",
"myKey3":"myVal3"
}
}
"key7":"anotherValChangeByMe",
"key8":"value8"
}
Do i need to read the whole JSON file into a dynamic, and then change / add the things i need somehow ?
You can parse the JSON into a JObject, manipulate it via the LINQ-to-JSON API, then get the updated JSON string from the JObject.
For example:
string json = #"
{
""data"": {
""subData1"": {
""key1"": ""value1"",
""key2"": ""value2"",
""key3"": ""value3""
},
""subdata2"": {
""key4"": ""value4"",
""key5"": ""value5"",
""key6"": ""value6""
}
},
""key7"": ""value7"",
""key8"": ""value8""
}";
JObject root = JObject.Parse(json);
JObject data = (JObject)root["data"];
JObject newSubData = new JObject();
newSubData.Add("myKey1", "myValue1");
newSubData.Add("myKey2", "myValue2");
newSubData.Add("myKey3", "myValue3");
data.Add("newSubData", newSubData);
root["key7"] = "anotherValChangeByMe";
Console.WriteLine(root.ToString());
Output:
{
"data": {
"subData1": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
"subdata2": {
"key4": "value4",
"key5": "value5",
"key6": "value6"
},
"newSubData": {
"myKey1": "myValue1",
"myKey2": "myValue2",
"myKey3": "myValue3"
}
},
"key7": "anotherValChangeByMe",
"key8": "value8"
}
JSON is ultimately just a string. If you are working on the server side, then unless you want to try to parse out the JSON yourself, the easiest way is to use JSON.NET to deserialize it back into it's native object model. Of course, you can also do this on the client side with JSON.parse(), and add the value there, too.

Retrieving "images" from a JSON string retrived from Instagram API

Using C# and Visual Studio 2010 (Windows Form Project), InstaSharp and Newtonsoft.Json libraries.
I want to get the image url from the JSON string returned to me by the Endpoint Instagram API when I request for a particular hashtag.
I can so far retrive the JSON string.
I am trying to use Newtonsoft.Json to deserialize the object using the examples, but I probably dont understand the JSON string representation of the object properly.
Below is a simplified sample response I get from the api call tags/tag-name/media/recent from their documentation. source here
{
"data": [{
"type": "image",
"filter": "Earlybird",
"tags": ["snow"],
"comments": {
}
"caption": {
},
"likes": {
},
"created_time": "1296703536",
"images": {
"low_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distillery.s3.amazonaws.com/media/2011/02/02/f9443f3443484c40b4792fa7c76214d5_7.jpg",
"width": 612,
"height": 612
}
},
"id": "22699663",
"location": null
},
...
]
}
I want to get specifically the standard_resolution in the images part.
This is the revelevant code that I currently have.
//Create the Client Configuration object using Instasharp
var config = new InstaSharp.Endpoints.Tags.Unauthenticated(config);
//Get the recent pictures of a particular hashtag (tagName)
var pictures = config.Recent(tagName);
//Deserialize the object to get the "images" part
var pictureResultObject = JsonConvert.DeserializeObject<dynamic>(pictureResult.Json);
consoleTextBox.Text = pictureResult.Json;
var imageUrl = pictureResultObject.Data.Images;
Console.WriteLine(imageUrl);
I get the error: Additional information: Cannot perform runtime binding on a null reference
so imageUrl is indeed null when I debug, hence indicating I am not accessing it the right way.
Anyone can explain to me how to access different parts of this JSON String using Newtonsoft.Json?
Using Newtonsoft.Json
dynamic dyn = JsonConvert.DeserializeObject(json);
foreach (var data in dyn.data)
{
Console.WriteLine("{0} - {1}",
data.filter,
data.images.standard_resolution.url);
}
I wrote a plugin for .net which takes care of deserializing the json string and returning a data table. it is still in development but see if it helps. Instagram.NET on Github

Categories