How to itrate JSON object? - c#

I trying to get the id and email list from the JSON. How can i achieve this?
My JSON string is
{
"name":"name1",
"username":"name1",
"id":505,
"state":"active",
"email":"name1#mail.com",
},
{
"name":"name2",
"username":"name2",
"id":504,
"state":"active",
"email":"name2#mail.com",
}
My code is
Dictionary<string, string> engineers = new Dictionary<string, string>();
using (StreamReader r = new StreamReader(#"D:\project\Gitlap\EngineerEmail\jsonlist5.json"))
{
using (JsonTextReader reader = new JsonTextReader(r))
{
JObject o2 = (JObject)JToken.ReadFrom(reader);
string id = o2["id"].ToString();
string email = o2["email"].ToString();
engineers.Add(email, id);
}
}
class UserItems
{
public string id { get; set; }
public string email { get; set; }
}
I can able to get the first person`s mail ID and ID details. I need to iterate this JSON and get all the mail ID and ID.
I don`t know that how to iterate this JSON. I tried some method from the internet but that was not succeeded.
How can I do?

First thing is your JSON input is not valid json, you need to fix it. There are two issues in it. Its not collection of json objects and comma is missing between two objects.
Valid json should look like below.
[{
"name":"name1",
"username":"name1",
"id":505,
"state":"active",
"email":"name1#mail.com",
},
{
"name":"name2",
"username":"name2",
"id":504,
"state":"active",
"email":"name2#mail.com",
}]
Now define a c# class representing your json object.
public class User
{
public string name { get; set; }
public string username { get; set; }
public int id { get; set; }
public string state { get; set; }
public string email { get; set; }
}
Use JSON.Net library to deserialize it as shown below.
private void button1_Click(object sender, EventArgs e)
{
if(File.Exists("json1.json"))
{
string inputJSON = File.ReadAllText("json1.json");
if(!string.IsNullOrWhiteSpace(inputJSON))
{
var userList = JsonConvert.DeserializeObject<List<User>>(inputJSON);
}
}
}

JObject o2 = (JObject)JToken.ReadFrom(reader);
foreach(var obj in o2)
{
string id = obj["id"].ToString();
string Email= obj["Email"].ToString();
engineers.Add(email, id);
}

I would recommend using the Json.NET NuGet package to accomplish this.
Firstly, create a model to represent your JSON data. Typically I would capitalize the first letter of the property names here, but to keep it consistent with the JSON, they are lower case.
public class UserData
{
public string name { get; set; }
public string username { get; set; }
public int id { get; set; }
public string state { get; set; }
public string email { get; set; }
}
You will need to add a using for Json.NET
using Newtonsoft.Json;
Finally, you can load, and deserialize your data into a strongly typed list, which you can then use to populate your engineers dictionary.
string datapath = #"D:\project\Gitlap\EngineerEmail\jsonlist5.json";
Dictionary<string, string> engineers = new Dictionary<string, string>();
List<UserData> data = new List<UserData>();
using (StreamReader r = new StreamReader(datapath))
{
string json = r.ReadToEnd();
data = JsonConvert.DeserializeObject<List<UserData>>(json);
data.ForEach(engineer => engineers.Add(engineer.email, engineer.id.ToString()));
}
As mentioned in another answer, your JSON is also badly formed. This will need correcting before it will deserialize correctly. We just need to add a comma to separate the two objects, and wrap them both in a JSON array, with []
[
{
"name":"name1",
"username":"name1",
"id":505,
"state":"active",
"email":"name1#mail.com"
},
{
"name":"name2",
"username":"name2",
"id":504,
"state":"active",
"email":"name2#mail.com"
}
]
Improvements
As your Id field is an integer, it would be better to change your dictionary from
Dictionary<string, string> engineers = new Dictionary<string, string>();
into
Dictionary<string, int> engineers = new Dictionary<int, string>();
You will then be able to simplify your ForEach query slightly. The ForEach can also be moved outside of the using() block.
data.ForEach(engineer =>
engineers.Add(engineer.email, engineer.id));
Improved solution
This includes the improvements above, I've used var for brevity.
var datapath = #"D:\project\Gitlap\EngineerEmail\jsonlist5.json";
var engineers = new Dictionary<string, int>();
var data = new List<UserData>();
using (var r = new StreamReader(datapath))
{
var json = r.ReadToEnd();
data = JsonConvert.DeserializeObject<List<UserData>>(json);
}
data.ForEach(engineer =>
engineers.Add(engineer.email, engineer.id));

try to create class that represent the data in json object for example
Class obj
{
public int Id { get ; set; }
public string email { get ; set; }
public string username { get ; set; }
public string state { get ; set; }
public string email { get ; set; }
}
then
using System.Web.Script.Serialization;
var js = new JavaScriptSerializer();
List<obj> list = js.Deserialize<List<obj>>(jsonString);
after that you can access all list items id and email by using foreach

Related

Reading JSON file that is an array in C# with unknown keys

I am having trouble reading from this JSON file:
[
{
"id":"100",
"name": "myname",
"playlists": {
"unknown key": ["song 1", "song2"]
}
}
]
here is my guild class:
public class Guild{
public string id = "";
public string name = "";
public Dictionary<string, List<string>> playlists;
public Guild(string name, string id, Dictionary<string, List<string>> playlists){
this.name = name;
this.id = id;
this.playlists = playlists;
}
}
Im having trouble reading from this JSON file because of the unknown keys and the array that surrounds the entire JSON file. Can someone please help? What am I doing wrong?
You're using fields. Traditionally you should use properties:
public class Guild {
public string Id { get; set; }
public string Name { get; set; }
public Dictionary<string, List<string>> playlists { get; set; }
}
But the primary problem is that you need to deserialize into a List<Guild> or Guild[] since the input JSON is an array of Guild.
var guilds = JsonConvert.DeserializeObject<List<Guild>>(inputJson);
If you're using .NET 6, you could directly use JsonArray from System.Text.Json.Nodes. For instance, to get first unknown key:
using System.Text.Json;
using System.Text.Json.Nodes;
var json_string = #"
[
{
""id"":""100"",
""name"": ""myname"",
""playlists"": {
""unknown key"": [""song 1"", ""song2""]
}
}
]
";
var guild = JsonSerializer.SerializeToNode(JsonNode.Parse(json_string)) as JsonArray;
var firstUnknownKey = guild[0]["playlists"]["unknown key"][0];
WriteLine(firstUnknownKey); // Prints: song 1

get data from json array string to an string variable

I get from another app an HTTP request with a JSON payload like this:
{
"reportName": "myfile",
"type_1": "pdf",
"paramm": [
{ "REF": "value1"},
{ "whatevervalue2": "whatevervalue2" }
]
}
I receive the data and try to process it. I created a class to get the data from the JSON:
public class ReportId
{
public string reportName { get; set; }
public string type_1 { get; set; }
public object[] paramm { get; set; }
}
And here is the method where I process all the data on the API controller:
[HttpPost]
public IActionResult generate([FromBody] ReportId jsonResult)
{
try
{
var reportName = jsonResult.reportName;
var type = jsonResult.type_1;
var recParam = jsonResult.paramm;
//....
List<ReportParameter> parameters = new List<ReportParameter>();
foreach (var t in recParam)
{
string[] paramName;
paramName = t.ToString().Split(":");
parameters.Add(new ReportParameter()
{
Name = paramName[0],
Labels = new List<string>() { paramName[1] },
Values = new List<string>() { paramName[1] }
});
}
reportWriter.SetParameters(parameters);
//....
}
catch
{
return null;
}
}
I got no problems with reportName and type_1 but on paramm it gets kinda wonky. I need to get the values of that array from the JSON. I do manage to get them, but with "all the format". For example, after the split on the first one I would get:
"{\r\n \"REF\""
" \"value1\"\r\n}"
Is there any more elegant way to get the values from that paramm array without having to replace the characters that are not part of the "real" string?
Thanks in advance.
[EDIT for clarification]
On the JSON I'll get multiple parameters:
"paramm": [
{ "parameter1": "value1" },
{ "parameter2": "value2" },
{ "parameter3": "value3" }
]
The parameter name could be any word and the value could be any as well. Those parameters are being sent to an RDL to filter some queries, so I need to get the name (parameter1, 2, 3...) and its value and add it as a parameter on the iteration of each.
Yes, there is an easier way.
In your ReportId class, change the paramm member to be a List<Dictionary<string, string>> instead of object[].
public class ReportId
{
...
public List<Dictionary<string, string>> paramm { get; set; }
}
Then, in your generate method you can just get the key and value from each dictionary instead of needing to do string manipulation:
List<ReportParameter> parameters = new List<ReportParameter>();
foreach (var dict in recParam)
{
var kvp = dict.First();
parameters.Add(new ReportParameter()
{
Name = kvp.Key,
Labels = new List<string>() { kvp.Value },
Values = new List<string>() { kvp.Value }
});
}
I guess, Your ReportId class should be like this. I hope this will work.
public partial class ReportId
{
[JsonProperty("reportName")]
public string ReportName { get; set; }
[JsonProperty("type_1")]
public string Type1 { get; set; }
[JsonProperty("paramm")]
public Paramm[] Paramm { get; set; }
}
public partial class Paramm
{
[JsonProperty("REF", NullValueHandling = NullValueHandling.Ignore)]
public string Ref { get; set; }
[JsonProperty("whatevervalue2", NullValueHandling = NullValueHandling.Ignore)]
public string Whatevervalue2 { get; set; }
}

How to read json string in c#

I am trying to parse manually a string in json. This is how my json look like
{{
"dbViews": [
{
"viewID": 0,
"viewColumns": [
{
"dbTitle": "ColNmid",
"viewTitle": "string",
"activated": true,
"activatedLabel": "Afficher"
},
{
"dbTitle": "ColNmdelete",
"viewTitle": "string",
"activated": true,
"activatedLabel": "Afficher"
}
]
}
],
"AddViewName": "test"
}}
This is how i am trying to read it.
UserViewDto User = new UserViewDto();
dynamic obj = JObject.Parse(json);
User.id = obj.dbViews.viewID;
User.viewName = obj.AddViewName;
foreach (var item in obj.viewColumns)
{
if (obj.dbTitle == "ColNmid")
{
User.ColNmid = obj.viewTitle;
}
}
I can only read addViewName, i can't seem to access viewID or viewColumn.
Update:
after the comments I obviously miss the second array. Here my new code witch work
UserViewDto User = new UserViewDto();
dynamic obj = JObject.Parse(json);
User.viewName = obj.AddViewName;
foreach (var view in obj.dbViews)
{
User.id = view.viewID;
foreach (var item in view.viewColumns)
{
if (item.dbTitle == "ColNmid")
{
User.ColNmid = item.viewTitle;
}
}
}
Your json in question is invalid (extra { and } at start and end). It seems that you are using Newtonsoft's Json.NET library. Usual approach is to create model corresponding to your json structure and deserialize it:
public class Root
{
[JsonProperty("dbViews")]
public List<DbView> DbViews { get; set; }
[JsonProperty("AddViewName")]
public string AddViewName { get; set; }
}
public class DbView
{
[JsonProperty("viewID")]
public long ViewId { get; set; }
[JsonProperty("viewColumns")]
public List<ViewColumn> ViewColumns { get; set; }
}
public class ViewColumn
{
[JsonProperty("dbTitle")]
public string DbTitle { get; set; }
[JsonProperty("viewTitle")]
public string ViewTitle { get; set; }
[JsonProperty("activated")]
public bool Activated { get; set; }
[JsonProperty("activatedLabel")]
public string ActivatedLabel { get; set; }
}
var result = JsonConvert.DeserializeObject<Root>();
You don't need to include all properties in your class, you can include only needed ones.
If you don't want to create custom models and want to loop through the JObject properties in your case you can do it for example like that:
var jObj = JObject.Parse(json);
foreach(var view in jObj["dbViews"]) // dbViews is an array
{
Console.WriteLine(view["viewID"]);
foreach (var viewColumn in view["viewColumns"]) // viewColumns is an array
{
Console.WriteLine(viewColumn["dbTitle"]);
}
}

C# - How to parse json

I have a json string as following
string json = "{\"Method\":\"LOGIN\",\"Skill\":{\"1\":\"SKILL-1\",\"2\":\"SKILL-2\"}}";
I am using JavaScriptSerializer to parse json
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
var dict = oSerializer.Deserialize<Dictionary<string,object>>(json);
I am getting Method = LOGIN using following line
MessageBox.Show("Method = "+dict["Method"].ToString());
But how to get Skill in a loop. like
Skill
1 = SKILL-1
2 = SKILL-2
The value mapping to your Skill key is actually another Dictionary<string, object>. You can iterate it by casting the object:
string json = "{\"Method\":\"LOGIN\",\"Skill\":{\"1\":\"SKILL-1\",\"2\":\"SKILL-2\"}}";
var oSerializer = new JavaScriptSerializer();
var dict = oSerializer.Deserialize<Dictionary<string,object>>(json);
var innerDict = dict["Skill"] as Dictionary<string, object>;
if (innerDict != null)
{
foreach (var kvp in innerDict)
{
Console.WriteLine ("{0} = {1}", kvp.Key, kvp.Value);
}
}
Or, the alternative would be to map your object into a proper class and deserialize to it instead of a generic Dictionary<string, object>.
Suppose you have following class
public class Data
{
public string Method { get; set; }
public Skills Skill { get; set; }
// If you don't want to use Skills class then you can use this
//public Dictionary<int, string> Skills { get; set; }
}
public class Skills
{
public int Id { get; set; }
public string Skill { get; set; }
}
So you can Deserialize json into Data Object like this
Data deserializedData = JsonConvert.DeserializeObject<Data>(json);
You should declare your own class:
public class YourClassName
{
public string Method { get; set; }
public Dictionary<int, string> Skill { get; set; }
}
and deserialize the Json string like this:
var obj = oSerializer.Deserialize<YourClassName>(json);

Deserialize JSON into string

How can I deserialize:
{
"data": [
{"ForecastID":8587961,"StatusForecast":"Done"},
{"ForecastID":8588095,"StatusForecast":"Done"},
{"ForecastID":8588136,"StatusForecast":"Done"},
{"ForecastID":8588142,"StatusForecast":"Pending"}
]
}
to
class RawData
{
public string data { get; set; }
}
So, I just want to have
[
{"ForecastID":8587961,"StatusForecast":"Done"},
{"ForecastID":8588095,"StatusForecast":"Done"},
{"ForecastID":8588136,"StatusForecast":"Done"},
{"ForecastID":8588142,"StatusForecast":"Pending"}
]
as value of property data of RawData's class instance.
Using Json.Net
var obj = (JObject)JsonConvert.DeserializeObject(json);
var newJson = obj["data"].ToString();
or using built-in JavaScriptSerializer
var dict = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
var newjson = new JavaScriptSerializer().Serialize(dict["data"]);
It would have made far much more sense to deserialize this JSON structure to:
public class Forecast
{
public IEnumerable<ForecastData> Data { get; set; }
}
public class ForecastData
{
public int ForecastID { get; set; }
public string StatusForecast { get; set; }
}
which is pretty trivial with the JavaScriptSerializer class that's built into the framework:
string json = "your JSON data here";
IEnumerable<ForecastData> data = new JavaScriptSerializer()
.Deserialize<Forecast>(json)
.Data;
or if you don't want to define models you could do that:
dynamic result = new JavaScriptSerializer().DeserializeObject(json);
foreach (var item in result["data"])
{
Console.WriteLine("{0}: {1}", item["ForecastID"], item["StatusForecast"]);
}

Categories

Resources