i have the following JSON i´m requesting from a service with C# using Newtonsoft.Json
[
{"Example1":value1,
"Example2":value1,
"Example3":"value1",
"ExampleList":
{"Example4":"",
"Example5":"value1",
"Example6":"value1",
"Example7":"",
"Example8":"value1"},
"Example9":["value1"],
"Example10":[]
}
]
the problem here are the "ExampleList", "Example9" and "Example10".
"ExampleList" list has no defined number of values. it can be 5, in the next query it can be 20.
I already have a similar request, where I only have the ExampleList without the values above it. I solved this with
Dictionary<string, string>
and it works fine.
My question is, how can I combine these two?
I tried something like this i found here Parsing JSON with dynamic properties
public partial class ExampleClass
{
public int Example1 { get; set; }
public long Example2 { get; set; }
public long Example3 { get; set; }
public ExampleList exampleList { get; set; }
}
public partial class ExampleList
{
Dictionary<string, string> exampleList = new Dictionary<string, string>();
}
Error:
JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Models.ExampleClass' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
Edit: Guru Strons solution worked. For Example 9 and 10 I created an array.
public class ExampleClass
{
public int Example1 { get; set; }
public int Example2 { get; set; }
public int Example3 { get; set; }
public Dictionary<string,string> ExampleList { get; set; }
public string[] Example9 { get; set; }
public string[] Example10 { get; set; }
}
var tempAttr = JsonConvert.DeserializeObject<List<ExampleClass>>(response);
If the goal is to deserialize dynamically only the ExampleList - there is no need to introduce class for it, just make property of type Dictionary<string, string>():
public partial class ExampleClass
{
public int Example1 { get; set; }
public long Example2 { get; set; }
public long Example3 { get; set; }
public Dictionary<string, string>() ExampleList { get; set; }
}
There is another problem - it seems that you are trying to deserialize to ExampleClass but your root json is array, so use List<ExampleClass> or another collection type:
JsonConvert.DeserializeObject<List<ExampleClass>>(...);
Related
I'm getting this json from an API.
string json = "{'serviceSession':{ '123123123':[{'apn':'abc'},{'apn':'bcd'},{'apn':'def'}]}}";
When I'm trying to deserialize it with
public class ServiceSession
{
public Dictionary<string, List<ServiceSessionType>> ServiceSessions { get; set; }
}
public class ServiceSessionType
{
public string Apn { get; set; }
}
and
var test = JsonConvert.DeserializeObject<ServiceSession> (json);
I'm getting null.
What's wrong? any ideas?
Thank you in advance!!
There is a missmatch between the datastructure and the json string. You need to change:
public class ServiceSession
{
//ServiceSessions replaced by serviceSession
public Dictionary<string, List<ServiceSessionType>> serviceSession { get; set; }
}
Another solution is to add a DataMember attribute which tells the deserializer the name.
[System.Runtime.Serialization.DataContract]
public class ServiceSession
{
[System.Runtime.Serialization.DataMember(Name = "serviceSession")]
public Dictionary<string, List<ServiceSessionType>> ServiceSessions { get; set; }
}
This makes sense if you can't change the class or the name is a keyword in C#.
I would like to deserialize the following JSON (using Json.NET) to an object, but cannot, as the class name would need to begin with a number.
An example of this is the Wikipedia article API. Using the API to provide a JSON response returns something like this. Note the "16689396" inside the "pages" key.
{
"batchcomplete":"",
"continue":{
"grncontinue":"0.893378504602|0.893378998188|35714269|0",
"continue":"grncontinue||"
},
"query":{
"pages":{
"16689396":{
"pageid":16689396,
"ns":0,
"title":"Jalan Juru",
"extract":"<p><b>Jalan Juru</b> (Penang state road <i>P176</i>) is a major road in Penang, Malaysia.</p>\n\n<h2><span id=\"List_of_junctions\">List of junctions</span></h2>\n<p></p>\n<p><br></p>"
}
}
}
}
How could I deserialize this JSON containing a number which changes based on the article?
It sounds like the Pages property in your Query class would just need to be a Dictionary<int, Page> or Dictionary<string, Page>.
Complete example with the JSON you've provided - I've had to guess at some of the name meanings:
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
public class Root
{
[JsonProperty("batchcomplete")]
public string BatchComplete { get; set; }
[JsonProperty("continue")]
public Continuation Continuation { get; set; }
[JsonProperty("query")]
public Query Query { get; set; }
}
public class Continuation
{
[JsonProperty("grncontinue")]
public string GrnContinue { get; set; }
[JsonProperty("continue")]
public string Continue { get; set; }
}
public class Query
{
[JsonProperty("pages")]
public Dictionary<int, Page> Pages { get; set; }
}
public class Page
{
[JsonProperty("pageid")]
public int Id { get; set; }
[JsonProperty("ns")]
public int Ns { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("extract")]
public string Extract { get; set; }
}
class Test
{
static void Main()
{
string text = File.ReadAllText("test.json");
var root = JsonConvert.DeserializeObject<Root>(text);
Console.WriteLine(root.Query.Pages[16689396].Title);
}
}
Related question: Json deserialize from wikipedia api with c#
Essentially you need to changes from using a class for the pages to a dictionary, which allows for the dynamic nature of the naming convention.
Class definitions :
public class pageval
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public string extract { get; set; }
}
public class Query
{
public Dictionary<string, pageval> pages { get; set; }
}
public class Limits
{
public int extracts { get; set; }
}
public class RootObject
{
public string batchcomplete { get; set; }
public Query query { get; set; }
public Limits limits { get; set; }
}
Deserialization :
var root = JsonConvert.DeserializeObject<RootObject>(__YOUR_JSON_HERE__);
var page = responseJson.query.pages["16689396"];
You can implement your own DeSerializer or editing the JSON before you DeSerialize it.
I'm currently working on a project where I make a request to the Riot Games API, parse the JSON, and do some stuff with it. I have the request working, and I know I'm getting valid JSON. My issue is using JSON.Net to deserialize the JSON.
The JSON is of the following structure:
{
"xarcies": {
"id": 31933985,
"name": "Farces",
"profileIconId": 588,
"revisionDate": 1450249383000,
"summonerLevel": 30
}
}
I want to load this data into the following class
[JsonObject(MemberSerialization.OptIn)]
class Summoner
{
[JsonProperty("id")]
public long id {get;set;}
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("profileIconId")]
public int profileIconId { get; set; }
[JsonProperty("revisionDate")]
public long revisionDate { get; set; }
[JsonProperty("summonerLevel")]
public long summonerLevel { get; set; }
}
The issue I'm having is that because I'm given a "xarcies" object that contains the information I need, I'm not sure how to go about designing a class that can accept the JSON data. I've seen some examples that use a RootObject class to take the object and that class has a subclass that all the pairs are put into, but I can't seem to get it to work. Every time I run it the attributes for the object end up being NULL.
You can deserialize your JSON as a Dictionary<string, Summoner>:
var root = JsonConvert.DeserializeObject<Dictionary<string, Summoner>>(jsonString);
The dictionary will be keyed by the user name, in this case "xarcies". See Deserialize a Dictionary.
I just used json2csharp to create the following class (its types look a bit different then yours):
public class UserData
{
public int id { get; set; }
public string name { get; set; }
public int profileIconId { get; set; }
public long revisionDate { get; set; }
public int summonerLevel { get; set; }
}
public class RootObject
{
public KeyValuePair<string, UserData> value { get; set; }
}
I have a weird JSON string which needs to be parsed in C#. How do I do it. I tried parsing it as a Dictionary but it failed. Can I somehow create a hashmap?
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(response);
The JSON string is here.
I am getting this data using a API. This is the error that i am receiving.
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
The shape of your JSON data won't fit in a Dictionary<string,string> because at its top level, it's not a dictionary. It's an array of objects.
You need to write a custom type (class) that matches the shape of your data, then deserialize to a collection of such types.
So, broadly speaking (with untested code...)
public class SomeType
{
public string notificationId{ get; set; }
//etc
public Dictionary<string,string> recruitersMap{ get; set; }
//etc
}
then
JsonConvert.Deserialize<List<SomeType>>(someJson)
this is because your JSON does not represent a Dictionary<string, string>. recruitersMap and jobsMap are both nested objects or collections, not strings.
you could create a POCO class
public class ApiEndPoint // you will find a better name, I'm sure
{
public string notificationId { get; set; }
public string readFlag { get; set; }
public string importantFlag { get; set; }
public string subject { get; set; }
public string folder { get; set; }
public DateTime creationTime { get; set; }
public int notificationCount { get; set; }
public string jobId { get; set; }
public Dictionary<string, string> recruitersMap { get; set; }
public Dictionary<string, string> jobsMap { get; set; }
}
and deserialize the json into a object of that class like this:
JsonConvert.DeserializeObject<List<ApiEndPoint>>(yourJsonString);
What I see is that the JSON you have pointed out has a regular structure and you should create a wrapping model for it see example below or play with it in https://dotnetfiddle.net/TGWTNC.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Newtonsoft.Json;
public class Program
{
public static void Main(string[] args)
{
var webClient = new WebClient();
var json = webClient.DownloadString("https://gist.githubusercontent.com/maskaravivek/33aa0d6556bbb9ecb77a/raw/b815daa55719a754eef5117321e2c0c5621c6a18/gistfile1.txt");
var notifications = JsonConvert.DeserializeObject<Notification[]>(json);
Console.WriteLine(notifications.Count());
Console.ReadLine();
}
}
//adjust the data types according to your needs
public class Notification
{
public string notificationId { get; set; }
public string readFlag { get; set; }
public string importantFlag { get; set; }
public string subject { get; set; }
public string folder { get; set; }
public string creationTime { get; set; }
public string notificationCount { get; set; }
public string jobId { get; set; }
public Dictionary<string, string> recruitersMap { get; set; }
public Dictionary<string, string> jobsMap { get; set; }
}
I am getting JSON that is being returned from a REST web service for survey responses. It has arrays for the name portion of some of the name value pairs. Additionally the names will be variable depending on the type of questions asked. I'm using JSON.net and trying to deserialize the returned value into some type of object tree that I can walk but can't figure out what structure to use to have it filled in.
I tested the following snippet in LinqPad and fields is always empty. Is there someway to easily read in the variable data or do I have to parse it in code?
void Main() {
string json = #"{
'result_ok':true,
'total_count':'51',
'data':[{
'id':'1',
'status':'Deleted',
'datesubmitted':'2015-01-12 10:43:47',
'[question(3)]':'Red',
'[question(4)]':'Blue',
'[question(18)]':12,
'[variable(\'STANDARD_IP\')]':'127.0.0.1',
'[variable(\'STANDARD_GEOCOUNTRY\')]':'United States'
}]
}";
var responses = JsonConvert.DeserializeObject<RootObject>(json);
responses.Dump();
}
public class RootObject {
public bool result_ok { get; set; }
public string total_count { get; set; }
public List<Response> data { get; set; }
}
public class Response {
public string id { get; set; }
public string status { get; set; }
public string datesubmitted { get; set; }
public List<object> fields = new List<object>();
}
Change the fields property in your Response class to be a Dictionary<string, object>, then mark it with a [JsonExtensionData] attribute like this:
public class Response
{
public string id { get; set; }
public string status { get; set; }
public string datesubmitted { get; set; }
[JsonExtensionData]
public Dictionary<string, object> fields { get; set; }
}
All of the fields with the strange property names will then be placed into the dictionary where you can access them as normal. No extra code is required.
Here is a demo: https://dotnetfiddle.net/1rQUXT