Lets say I get the following json data from a web service which I can't change.
[
[
"Header1",
"Header2",
"Header3",
"Header4"
],
[
"FirstValue1",
"FirstValue2",
"FirstValue3",
"FirstValue4"
],
[
"SecondValue1",
"SecondValue2",
"SecondValue3",
"SecondValue4"
]
]
jsonlint.com tells me that it is valid json and from what I know I would agree.
But somehow I'm wondering is there any "easy" way to deserialize this to a class. Each of the values in the second and third array belongs to the corresponding header in the first array.
I know how to use Json.NET but can't get my head around on how to use it with this data structure.
Simple - you can use JsonConvert.DeserializeObject to deserialize it to a string[][]:
using System;
using System.IO;
using Newtonsoft.Json;
class Test
{
static void Main()
{
var json = File.ReadAllText("test.json");
string[][] array = JsonConvert.DeserializeObject<string[][]>(json);
Console.WriteLine(array[1][3]); // FirstValue4
}
}
The easiest way is to use the string class and deserialzie it using Json.NET.
string[][] values = JsonConvert.DeserializeObject<string[][]>(json);
A better option could be to use
using Newtonsoft.Json.Linq
string json = #"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}";
JObject o = JObject.Parse(json);
string CPU = o.CPU;
int NumDrives = o.Drives.Count;
Source: http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_Parse.htm
Related
The point of the program is to find the total number of films a character has been a part of.
I'm trying to access a Newtonsoft.Json.Linq.JArray type object to count the length of a multidimensional array.
Json array:
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "descriptiontext",
"films": [
"linkapifilms1",
"linkapifilms2",
"linkapifilms3",
"linkapifilms6",
"linkapifilms7"
],
"species": [],
"vehicles": [
"linapivehicles14",
"linapivehicles30"
],
"starships": [
"linapistarships12",
"linapistarships22"
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "linkapipeople1"
}
]
}
I'm trying to access "films": to count the length of the array and store/display it on an int variable.
My Code:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class Solution
{
static void Main()
{
Console.WriteLine("Number of films: " + Run("Luke Skywalker"));
Console.ReadKey();
}
static public int Run(string character)
{
int numberOfFilms = 0;
Task<string> result = GetResponseString(character);
var jsonResult = result.Result;
dynamic dynamicResultObject = JsonConvert.DeserializeObject(jsonResult);
JArray x = dynamicResultObject.results;
//Find length of "films" code insert//
Console.WriteLine(character);
return numberOfFilms;
}
static public async Task<string> GetResponseString(string character)
{
var httpClient = new HttpClient();
var response = await httpClient.GetAsync("linktoapi/api/people/?search=" + character);
var contents = await response.Content.ReadAsStringAsync();
return contents;
}
}
I can access the first line of array with dynamicResultObject.results;
So the question is how do I access films, which is inside results and find the length?
Edit: I understand that this may not be the best way to go about writing this program however, is it not possible to just access the child array of the main array with the current code?
First of all, I would advise against using dynamic as it will just cause you headaches. If you're going to work with JObjects and JArrays anyway you're better off just using those types directly. The compiler will be able to detect errors earlier and you will get the Intellisense help in Visual Studio. So, parse your JSON like this:
JObject rootObject = JObject.Parse(jsonResult);
From that you can get your results array. (You were calling this array x in your code, but I think resultsArray is a more descriptive variable name):
JArray resultsArray = (JArray)rootObject["results"];
Like any array, if you want to get at a particular element you need to use its index. We can get the first element of the array (which is the object containing Luke Skywalker's data) like this:
JObject characterObject = (JObject)resultsArray[0];
From there, you can get the films property, which is also a JArray:
JArray filmsArray = (JArray)characterObject["films"];
To get the length of a JArray you use the Count property:
numberOfFilms = filmsArray.Count;
Fiddle: https://dotnetfiddle.net/iFAWB4
Now that you know how to drill down through the objects and arrays step-by-step, I'll show you a little shortcut, the SelectToken() method. This method allows you to specify a "path" to get a particular JToken (JObject and JArray are both types of JTokens). So, after parsing your JSON, you could get the films array directly like this:
JArray filmsArray = (JArray)rootObject.SelectToken("results[0].films");
and then get its count just like before.
Fiddle: https://dotnetfiddle.net/zOdSFs
When having the following code
var TermSource =
token.Value<JArray>("annotations")
.Values<string>("Term Source")
.FirstOrDefault();
I am able to get results for the following JSON block
"annotations": [
{
"Preferred Term": "Text1"
},
{
"Term Source": "Text2"
}
],
However, when running the following line
var country_code_iso3166_alpha2 =
token.Value<JArray>("datatype_properties")
.Values<string>("country_code_iso3166_alpha2")
.FirstOrDefault();
for the following JSON block
"datatype_properties": {
"country_name_iso3166_short": [
"Text Text"
],
"country_code_iso3166_alpha2": [
"txt1"
],
"country_code_iso3166_alpha3": [
"txt2"
],
"country_code_un_numeric3": [
"10"
]
I get the following error
'Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken'
How I should fix the LINQ statement to retrieve the value for the 'country_code_iso3166_alpha2' data
You're trying to access datatype_properties as if it's an array. It's not - it's another object with a property country_code_iso3166_alpha3 which has an array value.
You can call the Value method with a JObject type argument to get the object, then Value again with a JArray type argument to get the array. Here's a short but complete example:
using System;
using System.Linq;
using Newtonsoft.Json.Linq;
class Test
{
static void Main()
{
string json = #"{
'datatype_properties': {
'country_name_iso3166_short': [
'Text Text'
]
}
}".Replace("'", "\"");
JObject parent = JObject.Parse(json);
string countryName = parent["datatype_properties"]
.Value<JArray>("country_name_iso3166_short")
.Values<string>()
.FirstOrDefault();
Console.WriteLine(countryName);
}
}
Using JSON.Stringify I pass the following string inside another Stringify object.
[
[
"I-000-4310-000",
"Convention Registration",
"59.99"
],
[
"I-000-4311-000",
"Convention Breakout",
"39.99"
]
]
In my C# web service I need to split the string apart into a string array that looks like this:
string[, ,] GLCodes = new string[,,]
{
{
{ "I-000-4310-000", "Convention Registration", "59.99" },
{ "I-000-4311-000", "Convention Breakout", "9.99" }
}
};
What is the simplest way to do this?
Using Json.NET you can deserialize that list with this
string[][] strings = JsonConvert.DeserializeObject<string[][]>(jsonData);
Hope this helps!
Hi I am generating a JSON on my API that I am trying to use on codebehind C# in my web application but I cannot deserialize well.
My JSON has an object with JSON arrays and the element inside the array are dynamic so I cannot create a fixed class with those items becuase my JSON can have N ITEMS.
{
"MAINOBJET": [{
"ITEM1": "23800",
"ITEM2": "Dahl; Police",
"ITEM3": "test#test.net"
},
{
"ITEM1": "23802",
"ITEM2": "Steve ; Police",
"ITEM3": "test2#test.net"
}]
}
So how can I deserialize it to a DataTable, list or a Dictionary?
Thank you
here you can do some thing like the following this example should be able to get you started .. replace the structure / example with your Jason Text
lets say that my JSON Script looks like the following
{
"some_number": 253.541,
"date_time": "2012-26-12T11:53:09Z",
"serial_number": "SN8675309"
"more_data": {
"field1": 1.0
"field2": "hello JSON Deserializer"
}
}
assign you JSON jsonText to a variable and pass it to the following C# Code
using System.Web.Script.Serialization;
var jsonSerialization = new JavaScriptSerializer();
var dictObj = jsonSerialization.Deserialize<Dictionary<string,dynamic>>(jsonText);
Console.WriteLine(dictObj["some_number"]); //outputs 253.541
Console.WriteLine(dictObj["more_data"]["field2"]); //outputs hello JSON Deserializer
I have a following JSON repsonse from a API.
"{\"status\":\"True\", \"itemID\":\"201\"}".
On client side, how do I get values from status and itemID.
I am NOT working in javascript. This is a c# class.
Use library to work with json. For example, JSON.NET
Here is example:
string json = #"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""
]
}";
JObject o = JObject.Parse(json);
string name = (string)o["Name"];
// Apple
JArray sizes = (JArray)o["Sizes"];
string smallest = (string)sizes[0];
// Small
Take a look at this nifty C# 4.0 implementation http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx