Looping through a Json array (C#) - 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;
}

Related

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

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
}

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

Parse the fetched data in C#

I am new to C# and trying to write some code to fetch the webpage and parse it into readable format.
I have fetched the data from webpage using uri
var uri2 = new Uri("explame.com")
I see the response in format below like this:
{"name":"abc" "country":"xyz" "citizenship":"A" [{"pincode":"111", "Dis":"no"] Lot's of data follows something like that
There are multiple with attribute "name" and "country" in response. My question is how to fetch the data something like below
name:abc
country:xyz
citizenshih:A
pincode 111
dis:no
For all attributes in response code.
Is that the exact format of the data you're getting? Because that's JSON-ish, but it's not valid JSON and wouldn't be parsed as such. If, however, you are actually getting JSON then you can de-serialize that.
Using something like Newtonsoft's JSON library you can fairly trivially de-serialize JSON into an object. For example, this JSON:
{
"name":"abc",
"country":"xyz",
"citizenship":"A",
"someProperty": [
{
"pincode":"111",
"Dis":"no"
}]
}
Might map to these types:
class MyClass
{
public string Name { get; set; }
public string Country { get; set; }
public string Citizenship { get; set; }
public IEnumerable<MyOtherClass> SomeProperty { get; set; }
}
class MyOtherClass
{
public string Pincode { get; set; }
public string Dis { get; set; }
}
In which case de-serializing might be as simple as this:
var myObject = JsonConvert.DeserializeObject<MyClass>(yourJsonString);
you could try
dynamic data = JsonConvert.DeserializeObject(receivedJsonString);
foreach (dynamic o in data)
{
Debug.WriteLine(o.country);
}

Json deserialization with different variable names (FIXED Posted Solution)

Hello I'm working on a windows form application to enter in Magic The Gathering cards I have into a database for easy organization. In order to enter the card data fast I plan on using the MTG master card Json file which contains every card made and all of it's attributes. But the way they have the Json file doesn't seem to work well with the deserialization in Visual C#.
Here is what two entries look like:
{
"Air Elemental":{
(stuff that doesn't matter for the question)
},
"Ancestral Recall":{
. . .
}
}
As you can see the variable name for the data is different for every single one which is where the problem lies. I can't get C# to deserialize it correctly into a class because it wants the JsonProperty name and because it is different I can't really set it.
So if there is a way to specify that it doesn't need to have a specific name and it just stores what's placed in that variable I would really appreciate if you could tell me.
Thank you for any help you can provide.
SOLUTION
Thanks to Henrik I found out how to fix this problem. Here is what he posted:
dynamic data = JsonConvert.DeserializeObject(responseData);
IDictionary<string, JToken> cards = data;
foreach (var card in cards)
{
var key = card.Key;
var value = card.Value;
}
Which wasn't fully what I had to do but it laid out the ground of the solution. I figured out that the card.Value actually held all the Json text of the card so all I needed to do was use Json.DeserializeObject one more time but this time into my class that has all the values set to variables. Here's what it looks like
string json;
using (StreamReader sr = new StreamReader("G:/MTG Card Database/Files/AllCardsShort.json"))
{
json = sr.ReadToEnd();
sr.Close();
}
dynamic data = JsonConvert.DeserializeObject(json);
IDictionary<string, JToken> cards = data;
foreach (var card in cards)
{
CardData newCard = JsonConvert.DeserializeObject<CardData>(card.Value.ToString());
textBox1.Text = newCard.name; //Check to see if the name can be put into a textbox
break;
}
. . .
public class CardData
{
[JsonProperty("layout")]
public string layout { get; set; }
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("manaCost")]
public string manaCost { get; set; }
[JsonProperty("cmc")]
public string cmc { get; set; }
[JsonProperty("colors")]
public string[] colors { get; set; }
[JsonProperty("type")]
public string type { get; set; }
[JsonProperty("subtypes")]
public string[] subTypes { get; set; }
[JsonProperty("text")]
public string text { get; set; }
[JsonProperty("power")]
public string power { get; set; }
[JsonProperty("toughness")]
public string toughness { get; set; }
[JsonProperty("imageName")]
public string imageName { get; set; }
}
So again thank you Henrik for helping out. And thank you to everyone else that posted their idea as well!
Using Json.NET:
dynamic data = JsonConvert.DeserializeObject(responseData);
IDictionary<string, JToken> cards = data;
foreach (var card in cards)
{
var key = card.Key;
var value = card.Value;
}
Could this be what you are looking for? Check Tom Peplow's answer here
Deserialize JSON into C# dynamic object?
dynamic stuff = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
string name = stuff.Name;
string address = stuff.Address.City;

Parsing Json facebook c#

I am trying for many hours to parse a JsonArray, I have got by graph.facebook, so that i can extra values. The values I want to extract are message and ID.
Getting the JasonArry is no Problem and works fine:
[
{
"code":200,
"headers":[{"name":"Access-Control-Allow-Origin","value":"*"}],
"body":"{
\"id\":\"255572697884115_1\",
\"from\":{
\"name\":\"xyzk\",
\"id\":\"59788447049\"},
\"message\":\"This is the first message\",
\"created_time\":\"2011-11-04T21:32:50+0000\"}"},
{
"code":200,
"headers":[{"name":"Access-Control-Allow-Origin","value":"*"}],
"body":"{
\"id\":\"255572697884115_2\",
\"from\":{
\"name\":\"xyzk\",
\"id\":\"59788447049\"},
\"message\":\"This is the second message\",
\"created_time\":\"2012-01-03T21:05:59+0000\"}"}
]
Now I have tried several methods to get access to message, but every method ends in catch... and throws an exception.
For example:
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<dynamic>(json);
foreach (var item in result)
{
Console.WriteLine(item.body.message);
}
throws the exception: System.Collections.Generic.Dictionary doesnt contain definitions for body. Nevertheless you see in the screenshot below, that body contains definitions.
Becaus I am not allowed to post pictures you can find it on directupload: http://s7.directupload.net/images/120907/zh5xyy2k.png
I don't havent more ideas so i please you to help me. I need this for a project, private, not commercial.
Maybe you could give me an phrase of code, so i can continue my development.
Thank you so far
Dominic
If you use Json.Net, All you have to do is
replacing
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<dynamic>(json);
with
dynamic result = JsonConvert.DeserializeObject(json);
that's all.
You are not deserializing to a strongly typed object so it's normal that the applications throws an exception. In other words, the deserializer won't create an Anynymous class for you.
Your string is actually deserialized to 2 objects, each containing Dictionary<string,object> elements. So what you need to do is this:
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<dynamic>(s);
foreach(var item in result)
{
Console.WriteLine(item["body"]["message"]);
}
Here's a complete sample code:
void Main()
{
string json = #"[
{
""code"":200,
""headers"":[{""name"":""Access-Control-Allow-Origin"",""value"":""*""}],
""body"":{
""id"":""255572697884115_1"",
""from"":{
""name"":""xyzk"",
""id"":""59788447049""},
""message"":""This is the first message"",
""created_time"":""2011-11-04T21:32:50+0000""}},
{
""code"":200,
""headers"":[{""name"":""Access-Control-Allow-Origin"",""value"":""*""}],
""body"":{
""id"":""255572697884115_2"",
""from"":{
""name"":""xyzk"",
""id"":""59788447049""},
""message"":""This is the second message"",
""created_time"":""2012-01-03T21:05:59+0000""}}
]";
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<dynamic>(json);
foreach(var item in result)
{
Console.WriteLine(item["body"]["message"]);
}
}
Prints:
This is the first message
This is the second message
I am using this simple technique
var responseTextFacebook =
#"{
"id":"100000891948867",
"name":"Nishant Sharma",
"first_name":"Nishant",
"last_name":"Sharma",
"link":"https:\/\/www.facebook.com\/profile.php?id=100000891948867",
"gender":"male",
"email":"nihantanu2010\u0040gmail.com",
"timezone":5.5,
"locale":"en_US",
"verified":true,
"updated_time":"2013-06-10T07:56:39+0000"
}"
I have declared a class
public class RootObject
{
public string id { get; set; }
public string name { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string link { get; set; }
public string gender { get; set; }
public string email { get; set; }
public double timezone { get; set; }
public string locale { get; set; }
public bool verified { get; set; }
public string updated_time { get; set; }
}
Now I am deserializing
JavaScriptSerializer objJavaScriptSerializer = new JavaScriptSerializer();
RootObject parsedData = objJavaScriptSerializer.Deserialize<RootObject>(responseTextFacebook );

Categories

Resources