Deserialize JSON Data into a List in C# - c#

After hours of searching and trying, can someone please be so kind and help me solving this following simple problem:
I have the following JSON-String:
[
{
"key": 1234,
},
{
"key": 9876,
}
]
How can I read this JSON and write all values into a List?
Had many attempts so far, but please see following code:
List<int> content = new List<int>;
var json = reader.ReadToEnd();
var obj = JObject.Parse(json);
First try:
foreach(var key in obj)
{
content.Add((int)obj["key"]);
}
Other try:
var token = obj.SelectToken("key");
foreach(var item in token)
{
content.Add(JsonConvert.DeserializeObject<int>(item.value));
}
Or something this way?
foreach(var key in obj)
{
content.Add(Int32.Parse(obj.GetValue("key").ToString()));
}
Trying to run the last attempt, I get following error message:
Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray.
Even if the JSON looks like the following:
[{\"key\":9999},{\"key\":9876}]
Would be very happy for every answer.
Best regards

Use Newtonsoft.Json
It can be done in the following way:
List<string> yourList = JsonConvert.DeserializeObject(YourJson).ToList();
NOTE: It can only be saved as a list of strings , but can be called with: yourList.YourKeyName.

Depends on what you want but you could also create a specified class for your json.
The following class represents your json string.
public class RootObject
{
public int key { get; set; }
}
You could then deserialise your json string as follows:
string json=reader.ReadToEnd();
List<RootObject> myobs=JsonConvert.DeserialiseObject<List<RootObject>>(json);
You can then do stuffs with the list.
foreach(var ob in myobs){
Console.WriteLine(ob.key);
}

Following on to what #bolkay said, you need to define your object:
public class KeyClass
{
public int Key { get; set; }
}
and then if your JSON is in a variable called jsString for example
List<int> content = new List<int>();
var keys = JsonConvert.DeserializeObject<List<KeyClass>>(jsString);
foreach (var item in keys)
{
content.Add(item.Key);
}

Related

Parsing JSON list to int array in c#

I'm having trouble reading a JSON list of numbers into a c# int[] array.
I've tried several suggestions from SO, but none have worked.
How would I go about this using JSON.net?
Extract from JSON file:
{
"course": "Norsk",
"grades": [6, 3, 5, 6, 2, 8]
}
What I've tried in c#:
// Reads the JSON file into a single string
string json = File.ReadAllText(jfile);
Console.WriteLine(json);
// Parsing the information to a format json.net can work with
JObject data = JObject.Parse(json);
JToken jToken = data.GetValue("grades");
jGrades = jToken.Values<int>().ToArray();
and:
// Reads the JSON file into a single string
string json = File.ReadAllText(jfile);
Console.WriteLine(json);
// Parsing the information to a format json.net can work with
JObject data = JObject.Parse(json);
for (int o = 0; o < 6; o++) {
var grades = from p in data["Info"[i]] select (int)p["grades"[o]];
jGrades.Add(Convert.ToInt32(grades));
}
As you can see from the c# extracts, I've tried with both arrays and lists, but I can't get it to work.
With the first example (with an array) I get a System.NullRefrenceException, while with the List example, I get several errors, such as Unable to cast object of type 'whereselectlistiterator'2 [Newtonsoft.JSON] to type 'system.iconvertible'
Any help of tips are appreciated.
JObject.Parse(json) is your root object
JObject.Parse(json)["grades"] is the list/array
All you have to do is : converting the items to appropriate type
var list = JObject.Parse(json)["grades"].Select(x => (int)x).ToArray();
You can also declare a class
public class RootObject
{
public string course { get; set; }
public List<int> grades { get; set; }
}
and deserialize whole object as
var myobj = JsonConvert.DeserializeObject<RootObject>(json);
var grade = myobj.grades[0];
I would typically define a class with the relevant properties and simply convert the object.
public class CourseReport
{
public string Course { get; set; }
public ICollection<int> Grades { get; set; }
}
// Reads the JSON file into a single string
string json = File.ReadAllText(jfile);
Console.WriteLine(json);
// Parsing the information to a format json.net can work with
var courseReport = JsonConvert.DeserializeObject<CourseReport>(json);
foreach (var grade in courseReport.Grades)
{
Console.WriteLine(grade);
}

Create json in UWP without JSON.Net

I am trying to create a json formatted string using c# in UWP without JSON.Net, but I am just not understanding how to get there. Let's say I wanted to create the following json dynamically:
[{"id":130},{"id":131},{"id":132},{"id":133},{"id":134}]
From everything I have read, it would seem that I need a class that defines the content of my json. For example:
class accountTypes
{
public int id { get; set; }
public string type { get; set; }
}
From there, it would seem that I only need to create a list of type "accountTypes" and then add each "id" to the list.
List<accountTypes> jsonList = new List<accountTypes>();
int numOfChildren = AccountTypesList.Children.Count;
for (int i = 0; i < numOfChildren; i++)
{
if (((CheckBox)AccountTypesList.Children[i]).IsChecked == true)
{
jsonList.Add(new accountTypes() { id = (int)(double)((CheckBox)AccountTypesList.Children[i]).Tag });
}
}
While I am 99% sure that the above code is very flawed, it does not crash on me, so that is a start at least. What I am struggling with now though is how I would serialize the list "jsonList". Everything I have read thus far either points to JSON.net or the JavaScriptSerializer Class, and not Windows.Data.Json. If I could see a simple example on how to serialize json using Windows.Data.Json, then I could at least visualize what is going on with my list and could correct it accordingly. That being said, how do I serialize an array or a list using Windows.Data.Json?
First of all, there's no built-in JSON-serializer that handles all the mapping for you. This is exactly what JSON.NET is doing for you. Therefore, you have to take the manual and long way.
To create exactly this result:
[{"id":130},{"id":131},{"id":132},{"id":133},{"id":134}]
You have to use the JsonArray class. For example, pass your jsonList object to a method like this:
public string ToJson(List<accountTypes> objectList)
{
var jArray = new JsonArray();
foreach (var at in objectList)
{
jArray.Add(ToJson(at));
}
return jArray.ToString();
}
Whereas you use this method to create a JsonObject for your class object itself (as manual step as well):
public JsonObject ToJson(accountTypes at)
{
var jObj = new JsonObject();
jObj.SetNamedValue("id", JsonValue.CreateNumberValue(at.id));
return jObj;
}

Retrieve JSON value with random generated value

I've got a JSON file that looks like this. It's basically a JSON file taken stright from Wikipedia using their API.
{
"batchcomplete": "",
"query": {
"pages": {
"31329803": {
"pageid": 31329803,
"ns": 0,
"title": "Wiki Title",
"extract": "<p><b>Your Wiki Title</b></p>"
}
}
}
}
The number generated under "pages" (which is the pageID) is random. I'm trying to retrieve the "extract" value, but I can't seem to get it.
I'm using Visual Studio & using NewtonSoft JSON.net for parsing. I've created a class for retrieving the data I want, and it looks like this.
public class WikiPage
{
public string title { get; set; }
public int pageid { get; set; }
public int ns { get; set; }
public string extract { get; set; }
}
I'm trying to bypass the JSON tree & get the value I want. The code I use to get the value are as follows:
static void Main(string[] args)
{
// Getting JSON string from file
string JSONString = File.ReadAllText("wiki.json");
JObject wikiSearchResult = JObject.Parse(JSONString);
IList<JToken> wikiPages = wikiSearchResult["query"]["pages"].Children().ToList();
JToken result = wikiPages[0];
var wp = JsonConvert.DeserializeObject<WikiPage>(result.ToString());
// Writing data
Console.WriteLine(wp.extract);
Console.ReadLine();
}
When I run the program program, I get an error:
An unhandled exception of type
'Newtonsoft.Json.JsonSerializationException' occurred in
Newtonsoft.Json.dll
Additional information: Error converting value "31329803" to type
'JSON_test.WikiPage'. Path '', line 1, position 10.
I've tried many things, but no luck. Maybe there is a simpler way to do it, but I'm pretty much stuck right now, can someone help me?
You're almost done, just get result this way:
JToken result = wikiPages[0].Children().First();
You can't deserialize a key value pair like that. Try this instead :
var json = JObject.Parse(JSONString);
var pages = json["query"]["pages"].ToObject<Dictionary<string, WikiPage>>();
var page = pages.First().Value;
Console.WriteLine(page.extract);

Can't get data from deserialized Json string

I am really confused as to why I can't access any data that I have deserialized from Json string. When I step through the process I can see that the data is there, I just can't access it.
I am placing the data into Dictionary<string, object>, it's Count is 2. It contains object{object[]} (which I read as an ArrayList of objects?), and an object with response information.
I'm not too fussed about the response information I need to access the objects in the ArrayList. I'm having no such luck, my code is below:
var output = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(await response.Content.ReadAsStringAsync());
I have tried to get just the ArrayList using output["List"] (List is the objects key) and can still see all of the objects inside but still can't access them. It's probably a simple fix, it always is, but I have been staring at this problem all day and just can't make sense of it so could do with another pair of eyes.
Thanks
EDIT
The Json string is in the following format:
{"List":[{"Id":1,"intProperty":2,"boolProperty":false},{"Id":2,"intProperty":3,"boolProperty":false},{"Id":4,"intProperty":5,"boolProperty":false}],"ResponseInformation":{Other info here}}
Deserialize it into a class:
public class ListClass
{
public int Id;
public int IntProperty;
public bool boolProperty;
}
and then
var output = new JavaScriptSerializer().Deserialize<Dictionary<string, ListClass>>(await response.Content.ReadAsStringAsync());
And that should work!
I have figured out a long winded way of getting the information I need, If anyone can see a way to condense the code I'm open to suggestions :)
First I created my Currency class
public class Currency
{
public int CurrencyId { get; set; }
public int GlobalCurrencyId { get; set; }
public bool Archived { get; set; }
}
Next I deserialized my Json as I did in my question
var output = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(await response.Content.ReadAsStringAsync());
Next is the long winded bit; I used a foreach statement to get each element of my output variable. It was then made clear that the data inside was an array of dictionary objects so I created a list of Currency class objects:
var currencyObject = output["List"];
List<Currency> currencyList = new List<Currency>();
Currency item;
ArrayList myList = currencyObject as ArrayList;
foreach (object element in myList)
{
Dictionary<string, object> L1 = element as Dictionary<string, object>;
item = new Currency();
item.CurrencyId = Convert.ToInt32(L1["CurrencyId"]);
item.GlobalCurrencyId = Convert.ToInt32(L1["GlobalCurrencyId"]);
item.Archived = Convert.ToBoolean(L1["Archived"]);
currencyList.Add(item);
}
Figured it out in just two lines!!
var json = response.Content.ReadAsStringAsync().Result;
IList<Currency> output = new JsonSerializer().Deserialize<IList<Currency>>(new JsonTextReader(new StringReader(json)));

C# : asp.net 3.5 : Deserialize JSON - how to get each object string?

i know there is other places that give this answer but what i am trying to achieve is more complicated, this is my code for deserialization :
this is the json data for exemple :
data = #"{""ShiftID"":""2"",""EmpName"":""dsdsfs""}";
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
List<string> list = new List<string>(values.Keys);
// Loop through list
foreach (string k in list)
{
System.Diagnostics.Debug.Print("'{0}', '{1}'", k, values[k]);
}
this will return ShiftID,2 and EmpName, dsdsfs like you know but!
What happen if my json string look like this with multiple values :
data = #"{""ShiftID"":""2"",""EmpName"":""dsdsfs""},{""ShiftID"":""4"",""EmpName"":""dsdsfd""}";
Thanks!
What happen if my json string look like this with multiple values
data = #"{""ShiftID"":""2"",""EmpName"":""dsdsfs""}, {""ShiftID"":""4"",""EmpName"":""dsdsfd""}";
An error because this is not valid JSON. You probably meant:
data = #"[{""ShiftID"":""2"",""EmpName"":""dsdsfs""},{""ShiftID"":""4"",""EmpName"":""dsdsfd""}]";
Now you could deserialize into an array of dictionaries:
var values = JsonConvert.DeserializeObject<Dictionary<string, string>[]>(data);
foreach (var element in values)
{
foreach (var entry in element)
{
System.Diagnostics.Debug.Print("'{0}', '{1}'",
entry.Key,
entry.Value
);
}
}
or even better, define a model to represent your entities:
public class Employee
{
public string ShiftID { get; set; }
public string EmpName { get; set; }
}
and now deserialize into a list of employees:
var employees = JsonConvert.DeserializeObject<Employee[]>(data);
foreach (var employee in employees)
{
System.Diagnostics.Debug.Print("'{0}', '{1}'",
employee.ShiftID,
employee.EmpName
);
}
}
Thats invalid JSON. I think what you are looking for is a JSON array, which would enclose the entire string you have within brackets... [{"ShiftID": "2",...},{"ShiftId": "3",...}]

Categories

Resources