i am trying to get a value from a json file using c#. the json file looks more like the below string.
{
"results": [
{
"address_components": [
{
"long_name": "3",
"short_name": "3",
"types": [
"street_number"
]
}
],
"formatted_address": "3, Puppalaguda - Manikonda Main Rd, Sri Laxmi Nagar Colony, Manikonda, Hyderabad, Telangana 500089, India",
"geometry": {
"bounds": {
"northeast": {
"lat": 17.4025788,
"lng": 78.3748307
},
"southwest": {
"lat": 17.4019665,
"lng": 78.3733937
}
},
"location": {
"lat": 17.4023166,
"lng": 78.37417409999999
},
"location_type": "RANGE_INTERPOLATED",
"viewport": {
"northeast": {
"lat": 17.4036216302915,
"lng": 78.37546118029151
},
"southwest": {
"lat": 17.4009236697085,
"lng": 78.3727632197085
}
}
},
"place_id": "EmkzLCBQdXBwYWxhZ3VkYSAtIE1hbmlrb25kYSBNYWluIFJkLCBTcmkgTGF4bWkgTmFnYXIgQ29sb255LCBNYW5pa29uZGEsIEh5ZGVyYWJhZCwgVGVsYW5nYW5hIDUwMDA4OSwgSW5kaWE",
"types": [
"street_address"
]
}
]
}
I am looking for the formatted_address element from the json from C#. I am getting lost in JObject, JArray, JToken. I am trying to use NewtonSoft JSON. Thank you.
Using the LINQ-to-JSON API (JObjects) you can get the formatted address easily using the SelectToken method:
JObject obj = JObject.Parse(json);
string address = (string)obj.SelectToken("results[0].formatted_address");
Console.WriteLine(address);
Fiddle: https://dotnetfiddle.net/Fdvqkl
The easiest way would be to have model objects and then call
var rootObject = JsonConvert.DeserializeObject(jsonString);
With jsonString being your input. Then you can retrieve the formatted_address from the first array element like this like this:
var formattedAddress = rootObject.results[0].formatted_address;
Hope it helps.
using Newtonsoft.Json nuget . and do something like that
static void Main(string[] args)
{
string json = "{'results':[{'SwiftCode':'','City':'','BankName':'Deutsche Bank','Bankkey':'10020030','Bankcountry':'DE'},{'SwiftCode':'','City':'10891 Berlin','BankName':'Commerzbank Berlin (West)','Bankkey':'10040000','Bankcountry':'DE'}]}";
var resultObjects = AllChildren(JObject.Parse(json))
.First(c => c.Type == JTokenType.Array && c.Path.Contains("results"))
.Children<JObject>();
foreach (JObject result in resultObjects)
{
foreach (JProperty property in result.Properties())
{
// do something with the property belonging to result
}
}
}
// recursively yield all children of json
private static IEnumerable<JToken> AllChildren(JToken json)
{
foreach (var c in json.Children())
{
yield return c;
foreach (var cc in AllChildren(c))
{
yield return cc;
}
}
}
change JTokenType.Array to whatever the type u wish , also change the "results" to the property name you wish to extract
Related
I am working with an API that uses GraphQL and returns JSON data and I want to deserialize the JSON content dynamically rather than map the entire service structure in my application into C# data structures (.NET types/classes).
I've done this before but the JSON data was quite simple and straightforward. However, the this API I'm working with returns more complex/verbose JSON and I'm struggling to parse it properly.
Can anyone advise on how to parse the below JSON? That is, how to access the dynamic JSON's objects/properties.
I'm using Newtonsoft.Json. This is my code to deserialize:
byte bC = 0;
string location_text = string.Empty;
string location_value = string.Empty;
dynamic results = JsonConvert.DeserializeObject<dynamic>(json);
foreach (dynamic d in results)
{
bC = d.data.locationSuggestions.Count; // d.locationSuggestions.Count
for (byte b = 0; b < bC; b++)
{
location_text = d.data.locationSuggestions[b].location.contextualName;
location_value = d.data.locationSuggestions[b].location.id.value;
}
}
When I run this code I get an error that says "data" or "locationSuggestions" cannot be found.
The JSON I'm trying to parse is as follows:
{
"data": {
"locationSuggestions": [
{
"location": {
"id": {
"value": "seekAnzPublicTest:location:seek:2dkY4vZJF"
},
"name": "Brisbane",
"contextualName": "Brisbane QLD 4000 AU",
"countryCode": "AU",
"parent": {
"id": {
"value": "seekAnzPublicTest:location:seek:2FjxhQans"
},
"name": "CBD & Inner Suburbs",
"parent": {
"id": {
"value": "seekAnzPublicTest:location:seek:32XZdsa2K"
},
"name": "Brisbane"
}
}
}
},
{
"location": {
"id": {
"value": "seekAnzPublicTest:location:seek:2ckmimaF1"
},
"name": "Brisbane Grove",
"contextualName": "Brisbane Grove NSW 2580 AU",
"countryCode": "AU",
"parent": {
"id": {
"value": "seekAnzPublicTest:location:seek:2UC23LszP"
},
"name": "Southern Highlands & Tablelands",
"parent": {
"id": {
"value": "seekAnzPublicTest:location:seek:FTwZdE2K"
},
"name": "New South Wales"
}
}
}
}
]
},
"extensions": {
"requestLatency": 171
}
}
Regarding your JSON string, you can use dynamic to parse it and access the data as shown below:
You can also find a working example at: https://dotnetfiddle.net/lnhwJz
using System;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var jsonString=#"{'data':{'locationSuggestions':[{'location':{'id':{'value':'seekAnzPublicTest:location:seek:2dkY4vZJF'},'name':'Brisbane','contextualName':'Brisbane QLD 4000 AU','countryCode':'AU','parent':{'id':{'value':'seekAnzPublicTest:location:seek:2FjxhQans'},'name':'CBD & Inner Suburbs','parent':{'id':{'value':'seekAnzPublicTest:location:seek:32XZdsa2K'},'name':'Brisbane'}}}},{'location':{'id':{'value':'seekAnzPublicTest:location:seek:2ckmimaF1'},'name':'Brisbane Grove','contextualName':'Brisbane Grove NSW 2580 AU','countryCode':'AU','parent':{'id':{'value':'seekAnzPublicTest:location:seek:2UC23LszP'},'name':'Southern Highlands & Tablelands','parent':{'id':{'value':'seekAnzPublicTest:location:seek:FTwZdE2K'},'name':'New South Wales'}}}}]},'extensions':{'requestLatency':171}}";
var parsedData=JsonConvert.DeserializeObject<dynamic>(jsonString);
foreach(var item in parsedData.data.locationSuggestions)
{
Console.WriteLine(item.location.name);
Console.WriteLine(item.location.id.value);
Console.WriteLine(item.location.contextualName);
}
}
}
Output:
Brisbane
seekAnzPublicTest:location:seek:2dkY4vZJF
Brisbane QLD 4000 AU
Brisbane Grove
seekAnzPublicTest:location:seek:2ckmimaF1
Brisbane Grove NSW 2580 AU
Can you help me parse the values in 'realEstateProperties' attribute (ex. serial number and economyType.value). Here is a part of the json file:
{
"Entity1": {
"id": "5f514d20744a1fb",
"realEstateProperties": [
{
"serialNumber": "11",
"cadastralSections": [
{
"id": "5f514dc11a1e3",
"economyType": {
"value": "landRegisterPage.type",
}
}
],
"landRegisterPage": {
"id": "3456",
"landRegisterBook": {
"abbreviation": null
},
"note": "LRP",
"tags": null
},
"propertyTextBlock": null
}
],
"customFields": [],
Here is what I currently have:
public static string[] GetJsonValues(string jsonProperty)
{
testCaseName = "Entity1";
FixtureIncident.Root incObject = new FixtureIncident.Root();
incObject = LoadJSONFile();
JObject incJson = JObject.FromObject(incObject);
var attributes = incJson[testCaseName].ToList<JToken>();
var property = attributes.Find(i => i.ToObject<JProperty>().Name == jsonProperty) as JArray; //returns property=null
string[] Properties = property.ToObject<string[]>();
return Properties;
}
property returns null and I am not sure how to correct it.
I need to save all the realEstateProperties values in a string[].
I found some similar topics but I couldn't adjust my code so I make it works. Thanks in advance for your help.
I have a json like below
{
"name": "Ram",
"Age": "25",
"ContactDetails": {
"MobNo": "1"
}
}
Please suggest how to add
"Address": {
"No": "123",
"Street": "abc"
}
into ContactDetails
This should work (using Newtonsoft.Json)
var json =
#"{
""name"": ""Ram"",
""Age"": ""25"",
""ContactDetails"": {
""MobNo"": ""1""
}
}";
var jObject = JObject.Parse(json);
jObject["ContactDetails"]["Address"] = JObject.Parse(#"{""No"":""123"",""Street"":""abc""}");
var resultAsJsonString = jObject.ToString();
The result is:
{
"name": "Ram",
"Age": "25",
"ContactDetails": {
"MobNo": "1",
"Address": {
"No": "123",
"Street": "abc"
}
}
}
One of the options would be use Newtonsoft's Json.NET to parse json into JObject, find needed token, and add property to it:
var jObj = JObject.Parse(jsonString);
var jObjToExtend = (JObject)jObj.SelectToken("$.ContactDetails");
jObjToExtend.Add("Address", JObject.FromObject(new { No = "123", Street = "abc" }));
Just Deserialize the JSON into object, then insert the value that you need to insert to it.
Then, Serialize the object into JSON.
Reference: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to
How do i filter out to obtain the text ("I can provide....")? The program im using has no variable that contains just this text. Thanks!
{
"session_id": "9643039c-edf0-435a-8345-fc225859a6de"
}
{
"output": {
"generic": [
{
"response_type": "text",
"text": "I can provide you with directions, locations and operating hours as of now."
}
],
"intents": [
{
"intent": "Function",
"confidence": 0.30141472287041043
}
],
"entities": []
}
}
{}
Thanks...took me longer than it should have but here it the code:
string response = dialog.Message();
JObject data = JObject.Parse(response);
Console.WriteLine(data["output"]["generic"].First["text"]);
string text = data["output"]["generic"].First["text"].ToString();
I am fetching some data from external Webservice and parsing it to json using Newtonsoft.Json.Linq
like this
JObject o = JObject.Parse(json);
JArray sizes = (JArray) o["data"];
Now the Sizes looks like this
{
[
{
"post_id": "13334556777742_6456",
"message": "messagecomes her",
"attachment": {
"media": [
{
"href": "http://onurl.html",
"alt": "",
"type": "link",
"src": "http://myurl.jpg"
}
],
"name": "come to my name",
"href": "http://mydeeplink.html",
"description": "",
"properties": [],
},
}
]
}
I need to get "src": "http://myurl.jpg"element from this Json array.
I have tried:
foreach (JObject obj in sizes)
{
JArray media = (JArray)obj["attachment"];
foreach (JObject obj1 in media)
{
var src = obj1["src"];
}
}
But it's throwing an error:
Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'.
at this line
JArray media = (JArray)obj["attachment"];
Can any one give me a hand on this?
Try fix line
JArray media = (JArray)(obj["attachment"]);
to
JArray media = (JArray)(obj["attachment"]["media"]);
This is how I handled a scenario that sounds just like yours:
public static IList<Entity> DeserializeJson(JToken inputObject)
{
IList<Entity> deserializedObject = new List<Entity>();
foreach (JToken iListValue in (JArray)inputObject["root"])
{
Entity entity = new Entity();
entity.DeserializeJson(iListValue);
deserializedObject.Add(entity);
}
return deserializedObject;
}
public virtual void DeserializeJson(JToken inputObject)
{
if (inputObject == null || inputObject.Type == JTokenType.Null)
{
return;
}
inputObject = inputObject["entity"];
JToken assertions = inputObject["assertions"];
if (assertionsValue != null && assertionsValue.Type != JTokenType.Null)
{
Assertions assertions = new Assertions();
assertions.DeserializeJson(assertionsValue);
this.Assertions = assertions;
}
// Continue Parsing
}