I have an array of objects like this in json format:
{"results":[{"SwiftCode":"","City":"","BankName":"Deutsche Bank","Bankkey":"10020030","Bankcountry":"DE"},{"SwiftCode":"","City":"10891 Berlin","BankName":"Commerzbank Berlin (West)","Bankkey":"10040000","Bankcountry":"DE"}]}
What I want to get is a object[] in C#, where one object contains all the data what is in one json object. The thing is, I can NOT make a class with the properties of this object like here:
public class Result
{
public int SwiftCode { get; set; }
public string City { get; set; }
// .
// .
public string Bankcountry { get; set; }
}
Because I get everytime different results back, but I know it's always an array of objects. Someone knows how I could manage to get an array of objects back?
EDIT
I have to pass this object to powershell via WriteObject(results). So the ouput should only be the object IN the array.
Though this is an old question, I thought I'd post my answer anyway, if that helps someone in future
JArray array = JArray.Parse(jsonString);
foreach (JObject obj in array.Children<JObject>())
{
foreach (JProperty singleProp in obj.Properties())
{
string name = singleProp.Name;
string value = singleProp.Value.ToString();
//Do something with name and value
//System.Windows.MessageBox.Show("name is "+name+" and value is "+value);
}
}
This solution uses Newtonsoft library, don't forget to include using Newtonsoft.Json.Linq;
Use newtonsoft like so:
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
class Program
{
static void Main()
{
string json = "{'results':[{'SwiftCode':'','City':'','BankName':'Deutsche Bank','Bankkey':'10020030','Bankcountry':'DE'},{'SwiftCode':'','City':'10891 Berlin','BankName':'Commerzbank Berlin (West)','Bankkey':'10040000','Bankcountry':'DE'}]}";
var resultObjects = AllChildren(JObject.Parse(json))
.First(c => c.Type == JTokenType.Array && c.Path.Contains("results"))
.Children<JObject>();
foreach (JObject result in resultObjects) {
foreach (JProperty property in result.Properties()) {
// do something with the property belonging to result
}
}
}
// recursively yield all children of json
private static IEnumerable<JToken> AllChildren(JToken json)
{
foreach (var c in json.Children()) {
yield return c;
foreach (var cc in AllChildren(c)) {
yield return cc;
}
}
}
}
Use NewtonSoft JSON.Net library.
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
Hope this helps.
I have just got an solution a little bit easier do get an list out of an JSON object. Hope this can help.
I got an JSON like this:
{"Accounts":"[{\"bank\":\"Itau\",\"account\":\"456\",\"agency\":\"0444\",\"digit\":\"5\"}]"}
And made some types like this
public class FinancialData
{
public string Accounts { get; set; } // this will store the JSON string
public List<Accounts> AccountsList { get; set; } // this will be the actually list.
}
public class Accounts
{
public string bank { get; set; }
public string account { get; set; }
public string agency { get; set; }
public string digit { get; set; }
}
and the "magic" part
Models.FinancialData financialData = (Models.FinancialData)JsonConvert.DeserializeObject(myJSON,typeof(Models.FinancialData));
var accounts = JsonConvert.DeserializeObject(financialData.Accounts) as JArray;
foreach (var account in accounts)
{
if (financialData.AccountsList == null)
{
financialData.AccountsList = new List<Models.Accounts>();
}
financialData.AccountsList.Add(JsonConvert.DeserializeObject<Models.Accounts>(account.ToString()));
}
Using .NET 6 you could use built in System.Text.Json.Nodes
Example:
string json = #"{""results"":[{""SwiftCode"":"""",""City"":"""",""BankName"":""Deutsche Bank"",""Bankkey"":""10020030"",""Bankcountry"":""DE""},{""SwiftCode"":"""",""City"":""10891 Berlin"",""BankName"":""Commerzbank Berlin (West)"",""Bankkey"":""10040000"",""Bankcountry"":""DE""}]}";
JsonObject obj = JsonNode.Parse(json).AsObject();
JsonArray jsonArray = (JsonArray)obj["results"];
I believe this is much simpler;
dynamic obj = JObject.Parse(jsonString);
string results = obj.results;
foreach(string result in result.Split('))
{
//Todo
}
Related
TaskProperty.InternalAppConfiguration defines a JSON with various information and I need to get all the userGroups from this JSON. I only need names of the userGroups.
// saving task properties
foreach (var TaskProperty in representation.TaskProperties != null ? representation.TaskProperties : new List<TaskProperty>())
{
await this.taskRepository.AddTaskPropertyAsync(new TaskProperty()
{
ConnectionId = TaskProperty.ConnectionId,
NodeId = result.VertexIdPairs[Convert.ToInt16(TaskProperty.NodeId)],
TaskId = TaskProperty.TaskId,
InternalAppConfiguration = TaskProperty.InternalAppConfiguration,
IsApprovalTask = TaskProperty.IsApprovalTask
});
};
my JSON is looks like this,
in JSON visualizer it looks like this
how can I store all the userGroups into a single array or a list or something I can use in the future?
I've tried to deserialize using Newtonsoft, but I was unable to do anything. please help me out.. I really appreciate your answers and suggesions. Thank you!
Using Newtonsoft, this is what I would do:
public static IEnumerable<string> GetNamesFromJson(string json)
{
InternalAppConfiguration jsonObject = JsonConvert.DeserializeObject<InternalAppConfiguration>(json);
return jsonObject.OptionsData.UserGroups.Select(ug => ug.DisplayName);
}
public class InternalAppConfiguration
{
public OptionsData OptionsData { get; set; }
}
public class OptionsData
{
public List<UserGroup> UserGroups { get; set; }
}
public class UserGroup
{
public string DisplayName { get; set; }
}
I am working on WCF and I want to get record list array date wise and I need array key as the date which has common in record like below:
{
"EventAppGetAllSessionByCustomerIdResult":{
"02/22/2017":[
{
"SessionDate":"02/22/2017"
}
],
"08/27/2016":[
{
"SessionDate":"08/27/2016"
}
],
"Status":{
"Description":"Successfull!",
"Status":1
}
}
}
Basically, I want to extract values of SessionDate.
I assumed that you want to extract "SessionDate" property from your JSON. I recommend using JObject.Parse() method.
JObject jObject = JObject.Parse(json);
var result = (JObject)jObject["EventAppGetAllSessionByCustomerIdResult"];
var dates = new List<string>();
foreach(JProperty prop in result.Properties())
{
if (prop.Name != "Status")
{
var values = jObject["EventAppGetAllSessionByCustomerIdResult"][prop.Name].Values<string>("SessionDate");
dates.AddRange(values);
}
}
Little explanation:
In your case "02/22/2017" is property which has an array of objects. Each object has "SessionDate" property which holds value. So, following line will extract values from "SessionDate" of all objects:
var values = jObject["EventAppGetAllSessionByCustomerIdResult"][prop.Name].Values<string>("SessionDate");
values represents all dates from a single property. In your case, it can be from "02/22/2017" or from "08/27/2016".
dates will be list of "SessionDate" values. Of course, you have to handle possible exceptions by yourself.
I'm not sure its what you want but try this as your output object:
public class Session
{
public string SessionDate { get; set; }
}
public class Status
{
public string Description { get; set; }
public int Code { get; set; }
}
public class EventAppGetAllSessionByCustomerIdResult
{
public KeyValuePair<string, Session[]>[] EventAppGetAllSessionByCustomerId { get; set; }
public Status Status { get; set; }
}
I have the following JSON stored in a cookie that I wish to parse:
{"package":[{"id":"5054","nodeId":"3286"},{"id":"8888","nodeId":"7777"}], "hotel":[{"id":"3421","nodeId":"1234"},{"id":"8748","nodeId":"2435"}], "activity":[{"id":"5054","nodeId":"3286"},{"id":"8888","nodeId":"7777"},{"id":"2131","nodeId":"2342"}]}
I understand from the accepted answer on this question Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?) that you can use the following code to access individual objects within JSON notation:
JToken token = JObject.Parse(stringFullOfJson);
int page = (int)token.SelectToken("page");
int totalPages = (int)token.SelectToken("total_pages");
I've therefore adapted this into my code as follows:
HttpCookie cookie = Request.Cookies.Get("wishlist");
string JSONstring = string.Empty;
string nodeId = string.Empty;
if (cookie != null)
{
JSONstring = cookie.Value;
JToken token = JObject.Parse(JSONstring);
}
I now wish to only retreive the package array for example and loop through each of the items in this array and output the ids in the following format:
5054,8888
From the example code I sort of came up with the following approach but i'm not sure if i'm proceeding in the right direction.
JObject obj = JObject.Parse(JSONstring);
JArray packages = (JArray)obj["package"];
What is the best way of specifying one of the arrays eg. hotel, package , looping through their contents and outputting each of the id nodes that are found? The nodeId will always be numeric but the id could be a string or an int so this adds another layer of complication.
Any help would be greatly appreciated and I apologise if this is a sumwhat stupid or easy question however I have jsut started working with .Net and OO so some of the concepts are still a bit foggy.
Here's How I would Do This, I'd Create the classes required to Deserialize the JSON :-
public class JSONCookie
{
public Package[] package { get; set; }
public Hotel[] hotel { get; set; }
public Activity[] activity { get; set; }
}
public class Package
{
public string id { get; set; }
public string nodeId { get; set; }
}
public class Hotel
{
public string id { get; set; }
public string nodeId { get; set; }
}
public class Activity
{
public string id { get; set; }
public string nodeId { get; set; }
}
Now, I would Create a method that actually does the deserialising :-
public JSONCookie GetJSONCookieResponse()
{
try
{
// Add your own code that gets the Response Here.
// string response = "{"package":[{"id":"5054","nodeId":"3286"},{"id":"8888","nodeId":"7777"}], "hotel":[{"id":"3421","nodeId":"1234"},{"id":"8748","nodeId":"2435"}], "activity":[{"id":"5054","nodeId":"3286"},{"id":"8888","nodeId":"7777"},{"id":"2131","nodeId":"2342"}]}";
//return new JsonSerializer().Deserialize<JSONCookie>(new JsonTextReader(new StringReader(response)));
}
catch
{
return null;
}
}
From the JSONCookie Object that is returned, you can then use LINQ to pick out what you need like follows :-
x.package.Select(p=>p.id);
After a lot of trawling Google, this is the easiest solution I have come up with:
HttpCookie cookie = Request.Cookies.Get("wishlist");
string JSONstring = string.Empty;
string nodeId = string.Empty;
string test = string.Empty;
if (cookie != null)
{
JSONstring = cookie.Value;
JObject obj = JObject.Parse(JSONstring);
JArray packages = (JArray)obj["package"];
foreach (var item in packages.Children()){
var properties = item.Children<JProperty>();
var idElement = properties.FirstOrDefault(x => x.Name == "id");
var myElementValue = idElement.Value;
test = test + myElementValue + ",";
}
}
This will output all ids in the packages array in a CSV format (with a trailing ,)
I have the following issue with this json :
{
"EVTS": {
"EVT": [
{ "ID": "123456",
"KEY1" : "somekey",
"CATEG": [
"cat1",
"cat2",
"cat3"
]
}
]}
}
and this c# class:
public class myClass{
public string ID { get; set; }
public string KEY1 { get; set; }
public list<string> CATEG { get; set; }
}
public class ESObject1
{
[JsonProperty("EVT")]
public List<myClass> EVT { get; set; }
}
public class ESObject0
{
[JsonProperty("EVTS")]
public ESObject1 EVTS { get; set; }
}
}
here i call the deserializer :
ESObject0 globalobject = JsonConvert.DeserializeObject<ESObject0>(json);
But this last code doesnt work, i throws this exception : System.ArgumentException: Could not cast or convert from System.String to System.Collections.Generic.List1[System.String].`
Instead of list<string> i used string [] and only string nothing seems to work.
how can i deserialize this object correctly please.
Thank you.
There doesn't seem to be any apparent problem wit hyour code as this working example illustrates:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
public class myClass
{
public string ID { get; set; }
public string KEY1 { get; set; }
public List<string> CATEG { get; set; }
}
public class ESObject1
{
[JsonProperty("EVT")]
public List<myClass> EVT { get; set; }
}
public class ESObject0
{
[JsonProperty("EVTS")]
public ESObject1 EVTS { get; set; }
}
class Program
{
static void Main()
{
string json =
#"{
""EVTS"": {
""EVT"": [
{
""ID"": ""123456"",
""KEY1"": ""somekey"",
""CATEG"": [
""cat1"",
""cat2"",
""cat3""
]
}
]
}
}";
ESObject0 globalobject = JsonConvert.DeserializeObject<ESObject0>(json);
foreach (string item in globalobject.EVTS.EVT[0].CATEG)
{
Console.WriteLine(item);
}
}
}
Maybe you just fed a wrong json value to the deserializer which doesn't look like as the one shown in your question. By the way, the one shown i nyour question is invalid JSON as you are missing a , after KEY1 property declaration.
UPDATE:
Now that you have shown your real JSON (coming from http://donnees.ville.quebec.qc.ca/Handler.ashx?id=69&f=JSON) it appears that there's a row where CATEG is not an array of strings but a simple string:
""CATEG"": ""Conférence""
Now that's a pretty bad design because they are mixing arrays and simple properties. I am afraid that in order to deal with this situation you will need to use JObjects and extract the information you need by testing the actual underlying type.
For example:
var obj = JObject.Parse(json);
var events = (JArray)obj["EVTS"]["EVT"];
foreach (JObject evt in events)
{
var categories = evt["CATEG"];
if (categories is JArray)
{
// you've got a list of strings so you can loop through them
string[] cats = ((JArray)categories)
.Select(x => x.Value<string>())
.ToArray();
}
else
{
// you've got a simple string
string cat = categories.Value<string>();
}
}
I have done this many times with many many headaches. My advice is take the json output and use a tool similar to this to write your class for you (http://json2csharp.com/).
Then go over any nullable variables and add nullable type (ex. using int? for int) where needed.
I have the following Json string that I need to deserialize.
{"123456789":
{"short_description":"Delivered",
"detail_description":"Your item has been delivered"
}
}
The first field "123456789" is an id number, so basically this value can be different depending on the data being queried.
I'm using C# in visual studio. Obviously because the value of the first field can change I can't use a predefined class to deserialize the JSON into because this field will be used as the class name but the field value won't match the class name.
Is there a way to deserialize this into some sort of dynamic class but still access the fields as if it was a predefined class?
Alternatively is there a way to deserialize this into a predefined class even thought the class name doesn't match?
The service providing this data is a third party one so i don't have any control over it.
Here is one way which I use in production code. It might not be perfect, but it gets the job done.
using using System.Web.Script.Serialization;
// .....
public object GetJson(string url)
{
var json = Get(url); // I have code that makes this work, it gets a JSON string
try
{
var deserializer = new JavaScriptSerializer();
var result = deserializer.DeserializeObject(json);
return result;
}
catch (ArgumentException e)
{
// Error handling....
}
}
The object you receive back will be a generic Map, List, or whatever depending on the structure of the JSON. If you know what structure to expect, this is very useful without writing a customized parser or target object type.
You could then enumerate the keys of the Map, for example, to find your key that varies. A wrapper or conversion would then provide a consistent API to the rest of your application layer. Something like:
public class Order {
public string OrderNum { private set; get; }
public string ShortDesc { private set; get; }
public string Desc { private set; get; }
public static Order FromJson(object jsonResult)
{
var m = jsonResult as Map<string, object>;
// Handle errors, but I am not
var firstPair = m.First();
var detail = firstPair.Value as Map<string, object>;
var dummy = new Order()
{
OrderNum = firstPair.Key,
ShortDesc = detail["short_description"].ToString();
Desc = detail["detail_description"].ToString();
}
return dummy;
}
}
I liked answer above so I refactored it a bit. You'll need references to System.Web.Extensions.dll and System.Web.Script.Serialization.
Here's the class:
public class Order
{
public string OrderNum { private set; get; }
public string ShortDesc { private set; get; }
public string Desc { private set; get; }
public static Order FromJson(string jsonResult)
{
JavaScriptSerializer js = new JavaScriptSerializer();
// Should deserialize right to Dictionary<string, object>
// var result = ((Dictionary<string, object>)js.Deserialize<dynamic>(jsonResult)).First();
var result = js.Deserialize<Dictionary<string, object>>(jsonResult).First();
var detail = (Dictionary<string, object>)result.Value;
return new Order()
{
OrderNum = result.Key,
ShortDesc = detail["short_description"].ToString(),
Desc = detail["detail_description"].ToString()
};
}
}
And how to call it:
string json = "{\"123456789\": {\"short_description\":\"Delivered\", \"detail_description\":\"Your item has been delivered\" } }";
Order o = Order.FromJson(json);
You'll need to implement error handling on your own however.