How to Iterate Through the Following Json Using C#

Iterating over JSON object in C#

dynamic dynJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynJson)
{
Console.WriteLine("{0} {1} {2} {3}\n", item.id, item.displayName,
item.slug, item.imageUrl);
}

or

var list = JsonConvert.DeserializeObject<List<MyItem>>(json);

public class MyItem
{
public string id;
public string displayName;
public string name;
public string slug;
public string imageUrl;
}

.Net, How do I iterate through JSon object?

You can use the ToObject<T> method:

var Sprites = PokeObject["sprites"]
.ToObject<Dictionary<string, string>>()
.Select(x => x.Value)
.Where(x => x != null)
.ToList();

how to iterate through json array

"Map" is an array of JSON objects, so first you need to loop through the array, then you can loop through the key/value pairs of each object:

var blobObject = JObject.Parse(blob); 
var map = blobObject["Map"]; //it's a JToken at this point
//now let's parse each key/value pair in the map:
foreach (var item in map.Cast<JObject>()) // Map is an array of objects so loop through the array, then loop through the key/value pairs of each object
{
foreach (var pair in item)
{
var key = pair.Key;
var value = pair.Value;
}
}

Or if you prefer to flatten the array with LINQ's SelectMany():

foreach (var pair in map.SelectMany(o => (IDictionary<string, JToken>)o))
{
var key = pair.Key;
var value = pair.Value;
}

Notes:

  1. From the JSON spec

    JSON is built on two structures:

    • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
    • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

    A JSON array is mapped to a JArray while a JSON object is mapped to a JObject.

  2. How do we ... parse the values of the Map array? You don't need to parse the values of the Map array, they are already fully parsed. You just need to query them with LINQ to JSON.

Demo fiddle here.

Iterate through JSON with Arrays and Objects

Like we talk on the comments,
you need to deserialize your json

     private void btnConvert_Click(object sender, EventArgs e)
{
string fileName = "YOUR_PATH\\test.json";
string jsonString = File.ReadAllText(fileName);
Root2 l = JsonConvert.DeserializeObject<Root2>(jsonString);
tbResult.Text = "l.value[1].fields.SystemState.newValue.ToString()- \n" + l.value[1].fields.SystemState.newValue.ToString();

foreach (var item in l.value)
{
if (item.fields.SystemState != null)
{
if (item.fields.SystemState.newValue == "Resolved")
MessageBox.Show("ID - " + item.id);
//ADD HERE THE LOGIC YOU NEED TO UPDATE BY THE ID THE COUNTER
}
}
}

you need to use this classes to create the object l like my example.

public class RevisedBy
{
public string id { get; set; }
public string descriptor { get; set; }
}

public class SystemId
{
public int newValue { get; set; }
}

public class SystemReason
{
public string newValue { get; set; }
}

public class SystemCreatedDate
{
public DateTime newValue { get; set; }
}

public class SystemChangedDate
{
public DateTime newValue { get; set; }
}

public class SystemRev
{
public int oldValue { get; set; }
public int newValue { get; set; }
}

public class SystemState
{
public string oldValue { get; set; }
public string newValue { get; set; }
}

public class Fields
{
[JsonProperty("System.Id")]
public SystemId SystemId { get; set; }

[JsonProperty("System.Reason")]
public SystemReason SystemReason { get; set; }

[JsonProperty("System.CreatedDate")]
public SystemCreatedDate SystemCreatedDate { get; set; }

[JsonProperty("System.ChangedDate")]
public SystemChangedDate SystemChangedDate { get; set; }

[JsonProperty("System.Rev")]
public SystemRev SystemRev { get; set; }

[JsonProperty("System.State")]
public SystemState SystemState { get; set; }
}

public class Value
{
public int id { get; set; }
public int workItemId { get; set; }
public int rev { get; set; }
public RevisedBy revisedBy { get; set; }
public DateTime revisedDate { get; set; }
public Fields fields { get; set; }
}

public class Root2
{
public int count { get; set; }
public List<Value> value { get; set; }
}

and the result:
Sample Image

How do I iterate through items in a json object and retrieve a specific value in C#?

Depending on your requirements, you may want a much quicker and dirtier solution than Michaël's. If the contents of this JSON string are used in multiple places in your application, I urge you to write the classes and deserialize properly as he suggests. You'll be glad you did.

But if you only need one value from this JSON string in one place, this will work.

var jobj = JObject.Parse(json);
var user_name = "H281111";

var sys_id = jobj["result"]
.Where(r => (String)r["request_item.u_requested_for.user_name"] == user_name)
.Select(r => (String)r["request_item.u_requested_for.sys_id"])
.FirstOrDefault();

Elphas Tori suggests the following improvement using the ?[] (null-conditional element access) operator:

var sys_id2 = (string)jobj["result"]
.FirstOrDefault(r =>(string)r["request_item.u_requested_for.user_name"] == user_name)
?["request_item.u_requested_for.sys_id"];

If that LINQ code looks too much like gibberish to you, you can use a more conventional loop approach:

foreach (var r in jobj["result"])
{
// etc.
}

How to iterate JSON in C# and add every object to List?

I used exactly your json.

Create model:

public class Data
{
public int Id { get; set; }
public string ContentName { get; set; }
public string Content { get; set; }
public DateTime Created { get; set; }
}

Open namespace:

using Newtonsoft.Json.Linq;

Use this code:

var text = File.ReadAllText("test.json");
var json = JObject.Parse(text);
var list = new List<Data>();

foreach (var prop in json.Properties())
{
var value = prop.Value;
var data = new Data
{
Id = value["id"].Value<int>(),
ContentName = value["contentname"].ToString(),
Content = value["content"].ToString(),
Created = value["created"].Value<DateTime>()
};
list.Add(data);
}

C# looping over json object

Firstly you have to parse this JSON to C# class (or work with C# dynamic).
To do you, just copy your JSON data into the textbox in this web site and it will generate C# classes based on the JSON data format.

Take the classes it generated into your project.

Secondly you have to parse a JSON string data to C# classes. You can do it by:

YourClass data = Newtonsoft.Json.JsonConvert.DeserializeObject<YourClass>(jsonDataString);

Then you can iterate over the C# objects (in data) like you normally do.



Related Topics



Leave a reply



Submit