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;
}
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:
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);
}
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.
}
Looping through JSON array's object
You can use a Dictionary
to achieve the expected result without trouble:
var root = JsonConvert.DeserializeObject<RootObject>(result);
var report_row = root.data[0].report_row;
foreach (var reportRow in report_row)
foreach (var row in reportRow)
Console.WriteLine(row.Key + ", " + row.Value);
output example:
c1, 2019
c2, TEST123
c3, HERE IS C3
c1, 2019
c2, TEST345
c1, 2020
c2, TEST567
With the following model
public class C1
{
public string name { get; set; }
public string type { get; set; }
}
public class C2
{
public string name { get; set; }
public string type { get; set; }
}
public class ReportHeader
{
public C1 c1 { get; set; }
public C2 c2 { get; set; }
}
public class Datum
{
public ReportHeader report_header { get; set; }
public List<Dictionary<string, string>> report_row { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
public List<string> message { get; set; }
public int status { get; set; }
}
Try it online
Edit: Since OP updated the json, here is a outdated demo to try out. The idea of using a Dictionary
is exactly the same though.
c# iterate through json
You could try using Newtonsoft JSON Deserializer.
For your case you could do something like this:
Create a Track class with needed properties
Apply DeserializeObject
Track jsonObject = JsonConvert.DeserializeObject<Track >(json);
Iterate over jsonObject
.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();
Iterate through json object in c#
If you want to iterate through all tasks, you can use:
foreach (var task in project.tasks)
{
// do some stuff
}
or you can use LINQ to filter them, something like this:
foreach (var task in project.tasks.Where(t => t.id == "-1"))
{
// do some stuff
}
which is basically same with your example, with only difference that Where returns IEnumerable and not just Task like FirstOrDefault in your example.
Related Topics
Generics: Casting and Value Types, Why Is This Illegal
How to Delay Shutdown and Run a Process in Window Service
"Interface Not Implemented" When Returning Derived Type
Get Line Number for Xelement Here
C# Creating an Unknown Generic Type at Runtime
How to Get a Combination of Keys in C#
Executing Query with Parameters
Configureawait Pushes the Continuation to a Pool Thread
Changing Font for Richtextbox Without Losing Formatting
ASP.NET MVC Route to Catch All *.Aspx Requests
Cannot Find .Cs Files for Debugging .Net Source Code
How to Make the Xmlserializer Only Serialize Plain Xml
Create Object Instance Without Invoking Constructor
Can You Create SQL Views/Stored Procedure Using Entity Framework 4.1 Code First Approach