I have pretty big json string and I am trying to read into object in azure functions only small part of it and I am not sure how to do it.
Link to sample json https://learn.microsoft.com/en-us/azure/devops/service-hooks/events?view=azure-devops#workitem.updated
I tried to create class but I dont really know how to access "WorkItemType" from json because it looks nested into "Fields".
My code of object
public class jsonObject
public string System.WorkItemType { get; set; }
public string System.State { get; set; }
}
Deserializing here
dynamic eventData = await req.Content.ReadAsAsync<jsonObject>();
Try this:
public class jsonObject
public string WorkItemType { get; set; }
public string State { get; set; }
}
Deserialization:
jsonObject eventData = await req.Content.ReadAsAsync<jsonObject>();
eventData object contains your data
Related
I got this strange API response from one external service:
{emplooye: "Michael",age:"25",attachments:[{idAttachment: "23",attachmentPath:"C://Users/1"},{idAttachment: "24",attachmentPath:"C://Users/2"}]},{emplooye: "John",age:"30",attachments:{idAttachment: "25",attachmentPath:"C://Users/3"}}
Has anyone ever faced a situation where sometimes the "Attachment" property can be an array, sometimes it can be an object? I created a class to manipulate the data, but when I find an object, the code breaks.
I'm doing this in C#.
Class Used
public class Attachments
{
public string idAttachment{ get; set; }
public string attachmentPath{ get; set; }
}
public class Root
{
public string emplooye {get; set;}
public string age {get;set}
public List<Attachments> attachments { get; set; } = new List<Attachments>();
}
your json is not even close to json, should be something like this
var json = "[{\"emplooye\":\"Michael\",\"age\":\"25\",\"attachments\":[{\"idAttachment\":\"23\",\"attachmentPath\":\"C://Users/1\"},{\"idAttachment\":\"24\",\"attachmentPath\":\"C://Users/2\"}]},{\"emplooye\":\"John\",\"age\":\"30\",\"attachments\":{\"idAttachment\":\"25\",\"attachmentPath\":\"C://Users/3\"}}]";
Using Newtonsoft.Json you can create a JsonConstructor
using Newtonsoft.Json;
List<Data> data= JsonConvert.DeserializeObject<List<Data>>(json);
public class Data
{
public string emplooye { get; set; }
public string age { get; set; }
public List<Attachments> attachments { get; set; }
[JsonConstructor]
public Data(JToken attachments)
{
if (attachments.Type.ToString() == "Array")
this.attachments = attachments.ToObject<List<Attachments>>();
else
this.attachments = new List<Attachments> { attachments.ToObject<Attachments>() };
}
public Data() {}
}
public class Attachments
{
public string idAttachment { get; set; }
public string attachmentPath { get; set; }
}
You can use Newtonsoft to parse to a JToken which will handle the typing for you, but with the downside of not having a stable and predictable class to deserialize to automatically
Then, you would want to check its type, which returns a JTokenType enum
Once you know what the underlying types are, marshal the data into your DTO classes
JToken responseJT = JToken.Parse(json); //json string
if (responseJT.Type == JTokenType.Array)
//its an array, handle as needed ...
else if (responseJT.Type == JTokenType.Object)
//its an object, handle as needed ...
Personally, I would keep the attachments property as a List<Attachments> and if the JToken has a JSON object I would just set it as the [0] index of that property. This way things stay consistent and you can use LINQ on that property with ease
I'm trying to deserialize a json object into a c# object class. I checked how to read in a json file but I could only find examples for how to do this with a simple json but nothing about how to do it with a multi layer json like this:
{
"user":
{
"inventory":
{
"slot1": "item1",
"slot2": "item2",
}
}
}
invntory is not a simple string or int but another json object.
I couldn't even find out how a json object variable type is spelled in c# so that I can save the inventory object itself.
public object inventory;
didn't work.
By Using This Site https://json2csharp.com/ To Convert JSON To C# Class
public class Inventory {
public string slot1 { get; set; }
public string slot2 { get; set; }
}
public class User {
public Inventory inventory { get; set; }
}
// Main Class
public class Root {
public User user { get; set; }
}
Now Convert Your JSON To C# Class Object by Using https://www.nuget.org/packages/Newtonsoft.Json/
// JSON
string Json = "{'user': {'inventory': {'slot1': 'item1','slot2': 'item2'}}}";
// Desterilized Object
var myDeserializedClass = JsonConvert.DeserializeObject<Root>(Json);
I have a web service that is outputting JSON in the form
{"AppointmentList":[{"AppointmentList":{"id":"1","MeetingId":"1","MeetingName":"Test Meeting 1","Length":"90","Room":"B2C","DateTimeFrom":"1st Sept 2016","Venue":"The old pub","DateCreated":"2016-08-30 00:00:00","DateDue":"2016-09-01 00:00:00","UserId":"JohnsonPa"}},{"AppointmentList":{"id":"2","MeetingId":"2","MeetingName":"Test Meeting 2","Length":"60","Room":"B2C","DateTimeFrom":"11th Sept 2016","Venue":"The old pub","DateCreated":"2016-09-01 00:00:00","DateDue":"2016-09-12 00:00:00","UserId":"JohnsonPa"}...}]}
I am trying to deserialise this in to List. Normally, I would have a Base Class that would contain a property List AppointmentList {get; set;}, however, that would mean that I can't use type T and need a pile of duplicate code for each class.
I can certainly create BaseClass with a property public List Data {get; set;} however, as the JSON won't deserialise to Data (incorrect name) and the JSON PropertyName can't be set to the class name derived from typeof(T).ToString().
Is there a way to achieve what I'm trying to do without resorting to lots of code duplication?
I've tried casting the deserialiser to JArray and creating a reader from that, but this throws an exception.
Im not sure if this is exactly what you need, but maybe something like this would work? It allows you to successfully deserialize to a JArray like you state you tried at the end of your question.
JArray result = JsonConvert.DeserializeObject<dynamic>(json).AppointmentList;
Here how to convert it to List<object>
dynamic data = JsonConvert.DeserializeObject(json);
JArray array = data.AppointmentList;
List<object> objectList = array.ToObject<List<object>>();
What is wrong with generics? If you want a schemaless data structure use JObject or dynamic if not you can try this.
class Program
{
public const string json = #"{""AppointmentList"":[{""AppointmentList"":{""id"":""1"",""MeetingId"":""1"",""MeetingName"":""Test Meeting 1"",""Length"":""90"",""Room"":""B2C"",""DateTimeFrom"":""1st Sept 2016"",""Venue"":""The old pub"",""DateCreated"":""2016-08-30 00:00:00"",""DateDue"":""2016-09-01 00:00:00"",""UserId"":""JohnsonPa""}},{""AppointmentList"":{""id"":""2"",""MeetingId"":""2"",""MeetingName"":""Test Meeting 2"",""Length"":""60"",""Room"":""B2C"",""DateTimeFrom"":""11th Sept 2016"",""Venue"":""The old pub"",""DateCreated"":""2016-09-01 00:00:00"",""DateDue"":""2016-09-12 00:00:00"",""UserId"":""JohnsonPa""}}]}";
static void Main(string[] args)
{
var items = Newtonsoft.Json.JsonConvert.DeserializeObject<AppointmentItemList<Meeting1>>(json).GetList();
var items2 = Newtonsoft.Json.JsonConvert.DeserializeObject<AppointmentItemList<Meeting2>>(json).GetList();
Console.ReadLine();
}
public class AppointmentItemList<T>
{
public List<AppointmentItem> AppointmentList { get; set; }
public class AppointmentItem
{
public T AppointmentList { get; set; }
}
public IList<T> GetList()
{
return AppointmentList.Select(al => al.AppointmentList).ToList();
}
}
public class Meeting1
{
[Newtonsoft.Json.JsonProperty("id")]
public string Id { get; set; }
public string MeetingName { get; set; }
}
public class Meeting2
{
[Newtonsoft.Json.JsonProperty("id")]
public string Id { get; set; }
public string Room { get; set; }
}
}
I retrieve an information from Steam about a specific game. I provide an application url: http://store.steampowered.com/app/57690/ and get a JSON response like:
{
"57690":{ // this is dynamically got from application id above ^
"success":true
"data": { }
}
}
I have an object, SteamData
public bool success { get; set; }
public InternalData data { get; set; }
and InternalData
public string name { get; set; }
public string about_the_game { get; set; }
public string supported_languages { get; set; }
...
I tried to deserialize above json to SteamData using:
SteamData data = JsonConvert.DeserializeObject<SteamData>( thatJsonAbove );
It's not working because there exists a root which is an application id...
How to deserialize only what is inside root (in this example, what's inside "57690") ?
In case of using Newtonsoft JSON library you may try this:
JObject gameInfo = JObject.Parse(json);
SteamData data= gameInfo.SelectToken("57690", false).ToObject<SteamData>();
Since you know game's id - you can easily use this approach.
I have seen some other questions like this, but those are quite complex JSON data's that have objects within objects. Although the JSON I'm working with is never static, I doubt it's as complex as those. Also, it's my first time using JSON with C# so I'm a little clueless.
What I'm trying to achieve is to separate the data that is received from an API that I prompt using WebRequest in C#.
{
"johhny.debt": {
"id":35187540,
"name":"johnny.debt",
"profileIconId":786,
"Level":30,
"revisionDate":1428019045000
}
}
The returned JSON data is in a fashion like thereof.
I want to be able to access all of the properties of the above string in the following manner:
ID :
Name:
~~
~~
~~
... and so forth.
I'm assuming some type of class has to be made for this?
All help is appreciated, thank you all in advance.
Install Json.Net from Nuget
Install-Package Newtonsoft.Json
https://www.nuget.org/packages/Newtonsoft.Json/
Declare class for inner object ({"id":..., "name": ... }):
public class InnerObject
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Username { get; set; }
[JsonProperty("profileIconId")]
public int ProfileIconId { get; set; }
[JsonProperty("level")]
public int Level { get; set; }
[JsonProperty("revisionDate")]
public string RevisionDate { get; set; }
}
As you can see you can specify rename mapping from json fields to .Net object properties using JsonPropertyAttribute.
Read your json to Dictionary<string,InnerObject> and get value of "johhny.debt" key:
var dict = JsonConvert.DeserializeObject<Dictionary<string, InnerObject>>(jsonText);
var johhny = dict["johhny.debt"];
Or if your need always to parse exact json property 'johhny.debt', you could create root object class:
public class RootObject
{
[JsonProperty("johhny.debt")]
public InnerObject JohhnyDept { get; set; }
}
And deserialize it:
var root = JsonConvert.DeserializeObject<RootObject>(jsonText);
var johhny = root.JohhnyDebt;
Just Create a class like this
public class RootObject
{
public int Id { get; set; }
public string name { get; set; }
public int profileIconId { get; set; }
public int Level { get; set; }
public string revisionDate { get; set; }
}
then install json.Net and this code to your main method
var jsonObject=JsonConvert.DeserializeObject<RootObject>(jsonText);
That's all
Update
var obj = JObject.Parse(json);
var RootObject = new RootObject()
{
Id = (int)obj["johhny.debt"]["id"],
Level = (int)obj["johhny.debt"]["Level"],
name = (string)obj["johhny.debt"]["name"],
profileIconId = (int)obj["johhny.debt"]["profileIconId"],
revisionDate = (string)obj["johhny.debt"]["revisionDate"]
};