How do I loop through JSON to parse and display each item? - c#

I am trying to pull data and display it from a rest API using C#. However I am having trouble looping through it and displaying each individual item I have tried code like so
private void ParseAndDisplay(JsonValue json)
{
JsonValue teamData = json["teams"];
TextView name = FindViewById<TextView>(Resource.Id.txtName);
foreach(var team in teamData)
{
name.Text = team["name"];
}
}
What is it I do differently? For now I am simply trying to loop through and display all the teams "name" in one text view.

Ok.
lets assume this is your json object:
{"Tables":[
{"field1":1,"field2":2}
,{"field1":1,"field2":2
}]}
at first we create a object like this:
public class Table
{
public int field1 { get; set; }
public int field2 { get; set; }
}
public class RootObject
{
public List<Table> Tables { get; set; }
}
then just deserilize your json into object then iterate it like this:
var objs = JsonConvert.DeserializeObject<RootObject>(yourJson);
foreach(var t in objs.Tables)
{
//do something
}

Related

Looping through a Json array (C#)

I have been working on some automated tests with selenium and I need to get some data out of a JSON file.
how can i go about coding this, i have this so far
string json = File.ReadAllText("myfilepath");
dynamic data = jsonConvert.DeserializeObject(json);
string x = data[0].CountryName.Value;
foreach(var CN in data.countryName)
{
var CountryName = CN.CountryName;
}
I am a bit stuck on getting data through to loop it
Any help would be amazing guys
Example Json :
[
{
"CountryLookupId":123,
"CountryName":data,
"CountryLocation": moredata
}
]
I am trying to loop through the CountryName,i need to loop through 31 things
With out testing it. make a object model:
public class CountryClass
{
[JsonProperty("CountryLookupId")]
[JsonConverter(typeof(ParseStringConverter))]
public long CountryLookupId { get; set; }
[JsonProperty("CountryName")]
public string CountryName { get; set; }
[JsonProperty("CountryLocation")]
public string CountryLocation { get; set; }
}
Than deserialize list of object model:
List<CountryClass> data = jsonConvert.DeserializeObject<List<CountryClass>>(json);
Finally you can loop over your list of country objects:
foreach(var cn in data)
{
var countryName = cn.CountryName;
}

Deserialising json string to List<T>

I have a web service that is outputting JSON in the form
{"AppointmentList":[{"AppointmentList":{"id":"1","MeetingId":"1","MeetingName":"Test Meeting 1","Length":"90","Room":"B2C","DateTimeFrom":"1st Sept 2016","Venue":"The old pub","DateCreated":"2016-08-30 00:00:00","DateDue":"2016-09-01 00:00:00","UserId":"JohnsonPa"}},{"AppointmentList":{"id":"2","MeetingId":"2","MeetingName":"Test Meeting 2","Length":"60","Room":"B2C","DateTimeFrom":"11th Sept 2016","Venue":"The old pub","DateCreated":"2016-09-01 00:00:00","DateDue":"2016-09-12 00:00:00","UserId":"JohnsonPa"}...}]}
I am trying to deserialise this in to List. Normally, I would have a Base Class that would contain a property List AppointmentList {get; set;}, however, that would mean that I can't use type T and need a pile of duplicate code for each class.
I can certainly create BaseClass with a property public List Data {get; set;} however, as the JSON won't deserialise to Data (incorrect name) and the JSON PropertyName can't be set to the class name derived from typeof(T).ToString().
Is there a way to achieve what I'm trying to do without resorting to lots of code duplication?
I've tried casting the deserialiser to JArray and creating a reader from that, but this throws an exception.
Im not sure if this is exactly what you need, but maybe something like this would work? It allows you to successfully deserialize to a JArray like you state you tried at the end of your question.
JArray result = JsonConvert.DeserializeObject<dynamic>(json).AppointmentList;
Here how to convert it to List<object>
dynamic data = JsonConvert.DeserializeObject(json);
JArray array = data.AppointmentList;
List<object> objectList = array.ToObject<List<object>>();
What is wrong with generics? If you want a schemaless data structure use JObject or dynamic if not you can try this.
class Program
{
public const string json = #"{""AppointmentList"":[{""AppointmentList"":{""id"":""1"",""MeetingId"":""1"",""MeetingName"":""Test Meeting 1"",""Length"":""90"",""Room"":""B2C"",""DateTimeFrom"":""1st Sept 2016"",""Venue"":""The old pub"",""DateCreated"":""2016-08-30 00:00:00"",""DateDue"":""2016-09-01 00:00:00"",""UserId"":""JohnsonPa""}},{""AppointmentList"":{""id"":""2"",""MeetingId"":""2"",""MeetingName"":""Test Meeting 2"",""Length"":""60"",""Room"":""B2C"",""DateTimeFrom"":""11th Sept 2016"",""Venue"":""The old pub"",""DateCreated"":""2016-09-01 00:00:00"",""DateDue"":""2016-09-12 00:00:00"",""UserId"":""JohnsonPa""}}]}";
static void Main(string[] args)
{
var items = Newtonsoft.Json.JsonConvert.DeserializeObject<AppointmentItemList<Meeting1>>(json).GetList();
var items2 = Newtonsoft.Json.JsonConvert.DeserializeObject<AppointmentItemList<Meeting2>>(json).GetList();
Console.ReadLine();
}
public class AppointmentItemList<T>
{
public List<AppointmentItem> AppointmentList { get; set; }
public class AppointmentItem
{
public T AppointmentList { get; set; }
}
public IList<T> GetList()
{
return AppointmentList.Select(al => al.AppointmentList).ToList();
}
}
public class Meeting1
{
[Newtonsoft.Json.JsonProperty("id")]
public string Id { get; set; }
public string MeetingName { get; set; }
}
public class Meeting2
{
[Newtonsoft.Json.JsonProperty("id")]
public string Id { get; set; }
public string Room { get; set; }
}
}

Json Deserialize a webclient response C#

I am new in C# and I know there are hundreds of examples on the google for Json deserialization. I tried many but could not understand how C# works for deserialization.
using (var client = new WebClient())
{
client.Headers.Add("Content-Type", "text/json");
result = client.UploadString(url, "POST", json);
}
result looks like this:
{"Products":[{"ProductId":259959,"StockCount":83},{"ProductId":420124,"StockCount":158}]}
First I created a class:
public class ProductDetails
{
public string ProductId { get; set; }
public string StockCount { get; set; }
}
Then I tried to deserialize using this statement but couldn't understand.
var jsonresult = JsonConvert.DeserializeObject<ProductDetails>(result);
Debug.WriteLine(jsonresult.ProductId);
The above worked fine in visual basic with the following code but how to do this similar in C#
Dim Json As Object
Set Json = JsonConverter.ParseJson(xmlHttp.responseText)
For Each Product In Json("Products")
Debug.Print = Product("ProductId")
Debug.Print = Product("StockCount")
Next Product
You should use:
public class Product
{
public int ProductId { get; set; }
public int StockCount { get; set; }
}
public class RootObject
{
public List<Product> Products { get; set; }
}
var jsonresult = JsonConvert.DeserializeObject<RootObject>(result);
Because your JSON contains list of products, in jsonresult you have list of Product.
If you want get Product you can use eg. foreach
foreach(Product p in jsonresult.Products)
{
int id = p.ProductId;
}
Your JSON reads "an object that has a property named Products which contains an array of objects with properties ProductId and StockCount". Hence,
public class Inventory
{
public ProductDetails[] Products { get; set; }
}
var inventory = JsonConvert.DeserializeObject<Inventory>(result);
Your C# code cannot work because your json string contains values for 2 Product objects. As a result your var jsonresult variable will contain an array of Product objects, not one.
It is obvious in your VB code as you need to loop the Json variable in order to acquire each Product object.
Still your C# code would work if you string contained values for only one object like this:
{"ProductId" = 420124,"StockCount" = 158}
as you can see here http://www.newtonsoft.com/json/help/html/SerializingJSON.htm
Also you can try json parsing with JObject class, check this out: http://www.newtonsoft.com/json/help/html/t_newtonsoft_json_linq_jobject.htm

Parsing nested json with n number of json objects in c#

i am a newbie to coding , I have a nested json coming from a external source the json format is looks something like this ..
{
"data":"data",
"data":
{
"data":"data",
//----------------e.t.c the internal objects could be in n number
}
}
so how do i deserialize the json object and use the data as a list in order to do my other operations like sql and posting the data??
You need to create a class that is appropriate with the Json, like that:
public someClass
{
public string data1 { get; set; }
public DataClass dataArr { get; set; }
}
public DataClass
{
public string insideData { get; set; }
}
after you do this you need the following code:
var jsonDto = JsonConvert.DeserializeObject<someClass>(yourJson);

Create JSON object from c# class

I have a view model which looks like so:
public class CategoriesJsonViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public List<Description> UsedDescriptions { get; set; }
public List<Description> UnusedDescriptions { get; set; }
}
I am creating a List of CategoriesJsonViewModel in my controller and trying to send it to the client browser in Json format. I use Json() method to do that:
List<CategoriesJsonViewModel> categoriesVM = new List<CategoriesJsonViewModel>();
List<Category> categories = repo.GetAllCategories();
foreach(var i in categories)
{
CategoriesJsonViewModel categoryVM = new CategoriesJsonViewModel();
categoryVM.Id = i.Id;
categoryVM.Title = i.Title;
categoriesVM.Add(categoryVM);
categoryVM.UsedDescriptions = repo.GetUsedDescriptions(i.Id);
categoryVM.UnusedDescriptions = repo.GetUnusedDescriptions(i.Id);
}
return Json(categoriesVM);
Although the categoriesVM object is being built properly, I do not get appropriate Json object from it for some reason. Why is it so?
I suggest you get the outputted json and put into jsonlint.com
That'll help you find out what is causing the json to be invalid. It may be something to do with your definition of the Description object as your CategoriesJsonViewModel looks like it should be ok.

Categories

Resources