I have following json:
{
"Australia": {
"count": 2,
"records": {
"File1.ppt": {
"id": "123456789"
},
"File2.doc": {
"id": "987654321"
}
}
},
"PDFs.zip": {
"count": 0,
"records": {}
},
"Peru": {
"count": 2,
"records": {
"File3.PPT": {
"id": "897456123"
},
"File4.PPT": {
"id": "123546789"
}
}
},
"total count": 4
}
and to deserialize the above json I have defined some classes so that I can use these classes while deserializing my json into objects and below are the classes:
namespace GEO_Batch_Creation
{
[DataContract]
class BhpIdJson
{
[DataMember(Name = "objects")]
public Dictionary<string, Country[]> Countries { get; set; }
[DataMember(Name = "total count")]
public int TotalCount { get; set; }
}
[DataContract]
class Country
{
[DataMember(Name = "count")]
public int Count { get; set; }
[DataMember(Name = "records")]
public Dictionary<string, Record> Records { get; set; }
}
[DataContract]
class Record
{
[DataMember(Name = "filename")]
public string FileName { get; set; }
[DataMember(Name = "id")]
public Dictionary<string, string> BhpId { get; set; }
}
}
But when I use following code to deserialize the json I am getting only total count.
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
// Deserialization from JSON
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(BhpIdJson));
BhpIdJson bsObj2 = (BhpIdJson)deserializer.ReadObject(ms);
}
Please suggest me where I am doing mistake.
I don't think that this JSON is in correct format. I don't know if you got this from somewhere or made for yourself, but if the last one I recommend you to change the structure.
Even in C# you cant realy create a class that has the objects and the count of the object in the same List or Array etc.
Based on your class your JSON yhould look like this:
{
"objects": [
{
"name": "Australia",
"count": 2,
"records": [
{
"fileName": "File1.ppt",
"id": "123456789"
},
{
"fileName": "File2.doc",
"id": "987654321"
}
]
}
],
"total count": 4
}
As you can see you have to add Name or something to your Country class. I hope it helped.
Edit:
You can create a list like I mentioned above but it's not a good practice I think.
Related
I know there is a lot of similar questions and i tried to use it for last 12 h but without result. So please give me any advice how to solved my problem.
My json response look like this:
{
"status": "OK",
"products": {
"dynamic10259668": {
"ean": "4525348924",
"sku": "9384573245",
"name": "name1",
},
"dynamic10630436": {
"ean": "983623203943",
"sku": "9312763245",
"name": "name2"
},
"dynamic10634396": {
"ean": "1002904820",
"sku": "9384763245",
"name": "name3"
},
"dynamic10634398": {
"ean": "3400901100",
"sku": "9312763245",
"name": "name4"
},
"dynamic10634399": {
"ean": "8100103701",
"sku": "454763245",
"name": "name5"
},
"dynamic10634766": {
"ean": "5600904820",
"sku": "9384763245",
"name": "name6"
}
}
}
And models:
public class ProductsList
{
public string status { get; set; }
public ListProducts products { get; set; }
}
public class ListProducts
{
public ListProduct product { get; set; }
}
public class ListProduct
{
public string ean { get; set; }
public string sku { get; set; }
public string name { get; set; }
}
Now i need e.g. Directory<"dynamic10259668", "9384573245"> but don't know how to access to product value. I have try this code:
ProductsList productsList = JsonConvert.DeserializeObject<ProductsList>(response.Content);
foreach (ListProduct singleProduct in productsList.products.product)
{
Console.WriteLine(singleProduct.name);
}
My most common error is:
System.NullReferenceException: Object reference not set to an instance of an object.
You need to use a Dictionary<string, ListProduct>. I believe that will do what you want.
I kept your ListProduct class, but modified ProductsList to look like this:
public class ProductsList
{
public string status { get; set; }
public Dictionary<string, ListProduct> products { get; set; }
}
When I do that, this code properly deserializes your JSON:
var result = JsonConvert.DeserializeObject<ProductsList>(theJson);
You can get to the data for dynamic10259668 using something like:
if (result.products.TryGetValue("dynamic10259668", out var item))
{
Debug.WriteLine($"Name: {item.name}, Ean: {item.ean}, Sku: {item.sku}");
}
It looks like you were hoping for a dictionary of product name to ean. If that is all you need then the following code would work:
dynamic d = JObject.Parse(response.Content);
var productDictionary = new Dictionary<string, string>();
foreach (var product in d.products)
{
productDictionary[product.Name] = (string)product.Value.ean;
}
I'm currently working on a webservice, and I have this behavior that I haven't encountered until today. Here's the class I'm returning:
public class Block
{
public int order { get; set; }
public string title { get; set; }
public Dictionary<string, object> attributes { get; set; }
}
attributes can contain any kind of value: simple type, object, array, etc.
And when I return a Block object through my webservice, here's what I get:
{
"order": 1,
"attributes": [
{
"Key": "key1",
"Value": "value1"
},
{
"Key": "key2",
"Value": "value2"
}
],
"title": "Title"
}
Does anyone know why I'm not simply getting a "key1": "value1" output?
First of all your JSON is not valid, please be aware there are no , after "order": 1 this line.
After this correction you can change your class structure like this
public class Attribute
{
public string Key { get; set; }
public object Value { get; set; }
}
public class Block
{
public int order { get; set; }
public List<Attribute> attributes { get; set; }
public string title { get; set; }
}
this way you will be able to deserialize your JSON, I used simply this website https://json2csharp.com/ for converting your JSON into C# class
As for usage you can do .FirstOrDefault(x=>x.Key=="key1") to get whichever data you want, or if you will process all the list one by one you can simply do attributes.Count
When I do
var x = new Class
{
order = 1,
title = "Title",
attributes = new Dictionary<string, object>
{
{ "key1", "value1" },
{ "key2", "value2" }
}
};
var json = JsonConvert.SerializeObject(x);
Console.WriteLine(json);
I get
{"order":1,"title":"Title","attributes":{"key1":"value1","key2":"value2"}}
Do you have code that serializes your data or does ASP.NET do it for you?
im having trouble translating a json response from google's apis to DataContract classes. Specifically when trying to translate an int array from JSON to an int array in the DataContract.
Heres what I have done so far.
Heres the JSON response.
{
"kind": "youtubeAnalytics#resultTable",
"columnHeaders": [
{
"name": "views",
"columnType": "METRIC",
"dataType": "INTEGER"
},
{
"name": "likes",
"columnType": "METRIC",
"dataType": "INTEGER"
},
{
"name": "dislikes",
"columnType": "METRIC",
"dataType": "INTEGER"
}
],
"rows": [
[
2162435,
871,
907
]
]
}
And heres my Data Contract classes
[DataContract]
public class AnalyticsData
{
[DataMember(Name = "kind")]
public string Kind { get; set; }
[DataMember(Name = "columnHeaders")]
public ColumnRows[] ColumnHeaders { get; set; }
[DataMember(Name = "rows")]
public int[][] rows { get; set; } //<--------
}
[DataContract]
public class ColumnRows
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "columnType")]
public string ColumnType { get; set; }
[DataMember(Name = "dataType")]
public string DataType { get; set; }
}
The problem I am having is translating the 'rows' element from the JSON doc into DataContract variables, as as shown in the AnalyticsData class in the int array 'rows'.
The error I get when debugging is
System.Runtime.Serialization.SerializationException: There was an error deserializing the object of type StudioWP8.AnalyticsData. Input string was not in a correct format. ---> System.FormatException: Input string was not in a correct format.
Use jsonconvert and it will be ok
[TestMethod]
public void test()
{
string json =
"{ \"kind\": \"youtubeAnalytics#resultTable\", \"columnHeaders\": [ { \"name\":\"views\", \"columnType\": \"METRIC\", \"dataType\": \"INTEGER\" }, { \"name\": \"likes\", \"columnType\": \"METRIC\", \"dataType\": \"INTEGER\" }, { \"name\": \"dislikes\", \"columnType\": \"METRIC\", \"dataType\":\"INTEGER\" } ], \"rows\": [ [ 2162435, 871,907 ] ]}";
AnalyticsData d = JsonConvert.DeserializeObject<AnalyticsData>(json);
}
I am trying to acheive below JSON Object from c# code
{
"Animals": {
"name": "Animals",
"data": [
[
"Cows",
2
],
[
"Sheep",
3
]
]
},
"Fruits": {
"name": "Fruits",
"data": [
[
"Apples",
5
],
[
"Oranges",
7
],
[
"Bananas",
2
]
]
},
"Cars": {
"name": "Cars",
"data": [
[
"Toyota",
1
],
[
"Volkswagen",
2
],
[
"Opel",
5
]
]
}
}
I tried json2C# link and it gave me this class structure
public class Animals
{
public string name { get; set; }
public List<List<object>> data { get; set; }
}
public class Fruits
{
public string name { get; set; }
public List<List<object>> data { get; set; }
}
public class Cars
{
public string name { get; set; }
public List<List<object>> data { get; set; }
}
public class RootObject
{
public Animals Animals { get; set; }
public Fruits Fruits { get; set; }
public Cars Cars { get; set; }
}
My first problem is the classes generated by code is static (Animals,Fruits,Cars) in reality it could be more and less it is category and it may be some new categories so every time I need to create a new class for each category? how can I handle this?
Second how I populate from these classes the same structure.
Please bear with me as I am very beginner level programmer.
Try this. Create a new console application. You will need the JSON.NET library.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace ConsoleApplication7
{
class Item : List<object>
{
public Item()
{
this.Add(""); // for name;
this.Add(0); // for value;
}
[JsonIgnore]
public string Name { get { return this[0].ToString(); } set { this[0] = value; } }
[JsonIgnore]
public int Value { get { return (int)this[1]; } set { this[1] = value; } }
}
class Category
{
public string name { get; set; }
public List<Item> data { get; set; }
public Category()
{
this.data = new List<Item>();
}
}
class Program
{
static void Main(string[] args)
{
var all = new Dictionary<string, Category>
{
{
"Animals", new Category()
{
name = "Animals",
data =
new List<Item>()
{
new Item() {Name = "Cows", Value = 2},
new Item() {Name = "Sheep", Value = 3}
}
}
//include your other items here
}
};
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(all));
Console.ReadLine();
}
}
}
You don't need separate Animals, Fruits, etc. classes. They can be merged.
public class Category
{
public string name { get; set; }
public List<List<object>> data { get; set; }
}
And since the list of items in the root object can change, you should use a Dictionary<string, Category> instead of the RootObject class you had generated. Your JSON is not valid, (test it with http://jsonlint.com/), but this produces something like the first part of your example:
var dict = new Dictionary<string, Category>
{
{ "Animals", new Category
{
name = "Animals",
data = new List<List<object>>
{
new List<object> { "Cows", 2 },
new List<object> { "Sheep", 3 }
}
}
},
};
string serialized = JsonConvert.SerializeObject(dict, Formatting.Indented);
Produces the following (I'm using Json.NET for the serialization here). The other types would be similar. (see Object and Collection Initializers for more info on the list and dictionary initialization syntax I used, if you're unfamiliar with it; basically just shortcuts for their Add methods)
{
"Animals": {
"name": "Animals",
"data": [
[
"Cows",
2
],
[
"Sheep",
3
]
]
}
}
If you have a choice of what the data types should be, I think it'd be better to replace the List<object> with a class something like this, to be more clear:
public class Item
{
public string name { get; set; }
public int quantity { get; set; }
}
Install the JSON.NET library.
Then with the classes that were created:
string jsonStr = "{'Animals': {name: 'Animals', data: [['Cows', 2], ['Sheep', 3] ] },'Fruits': { name: 'Fruits', data: [['Apples', 5], ['Oranges', 7], ['Bananas', 2] ] }, 'Cars': { name: 'Cars', data: [ ['Toyota', 1], ['Volkswagen', 2], ['Opel', 5] ] } }";
RootObject Myobj = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(jsonStr);
I just got my json response as a string.My json is given below,
"code": 0,
"message": "success",
"students": {
"details":{
"hjeke": {
"id": "257633000000070001",
"name": "hjeke",
"percentage": 36,
"type": "Good",
},
"Second": {
"id": "257633000000073001",
"name": "Second",
"percentage": 4,
"type": "bad",
}
}
}
Like hjeke and Second there are many key value pairs,how can i deserialize my json using Newtonsoft.json
Try to understand my solution in your previous question
How to deserialize json data in windows phone?
Your first JSON in that question was good and simple to use.
JSON, where field names are unique not convinient to deserialize. So, you got problems such as public class Hjeke and public class Second for each instance, when you use code generator.
Use JSON-structure with list of students:
"code": 0,
"message": "success",
"students": [
{
"id": "257633000000070001",
"name": "hjeke",
"percentage": 36,
"type": "Good",
},
{
"id": "257633000000073001",
"name": "Second",
"percentage": 4,
"type": "bad",
}]
is good and flexible structure. Using this, you don't need to parse not obvious fields like
"details":{
"hjeke": {
and so on.
And work with them using classes, from my previous answer. The main idea - you need list of objects. public List<StudentDetails> students. Then, all students objects deserialized in List, which is easy to use.
As everybody mentioned your json seems to be very unflexible, huh.
You can extract the data you are interested in.
So this is your model:
public class StudentDetails
{
public string id { get; set; }
public string name { get; set; }
public int percentage { get; set; }
public string type { get; set; }
}
And this is how you can extract it:
var jsonObj = JObject.Parse(str);
// get JSON result objects into a list
var results = jsonObj["students"]["details"].Children().Values();
// serialize JSON results into .NET objects
var details = new List<StudentDetails>();
foreach (JToken result in results)
{
var st = result.ToString();
var searchResult = JsonConvert.DeserializeObject<StudentDetails>(st);
details.Add(searchResult);
}
I'm using a newtonsoft.json library here.
Your Response string has some mistakes man, its not a valid json
just small modification to be done as below:
{
"code": 0,
"message": "success",
"students": {
"details": {
"hjeke": {
"id": "257633000000070001",
"name": "hjeke",
"percentage": 36,
"type": "Good"
},
"Second": {
"id": "257633000000073001",
"name": "Second",
"percentage": 4,
"type": "bad"
}
}
}
}
you can make out the difference
Now Follow these steps:
1.Go to this link Json to C#
2.place your Json string there and generate C# class object
3.Now create this class in your solution
4.Now deserialize As below
var DeserialisedObject = JsonConvert.DeserializeObject<Your Class>(YourJsonString);
First, create the classes:
public class Hjeke
{
public string id { get; set; }
public string name { get; set; }
public int percentage { get; set; }
public string type { get; set; }
}
public class Second
{
public string id { get; set; }
public string name { get; set; }
public int percentage { get; set; }
public string type { get; set; }
}
public class Details
{
public List<Hjeke> hjeke { get; set; }
public List<Second> Second { get; set; }
}
public class Students
{
public List<Details> details { get; set; }
}
public class RootObject
{
public int code { get; set; }
public string message { get; set; }
public List<Students> students { get; set; }
}
After that, use JSON.NET to deserialize:
var deserialized = JsonConvert.DeserializeObject<Class1>(YourStringHere);
Do you have any influence over the json response? Details should probably be a JSONArray in this case, not an object with a varying amount of properties, since I assume that's what you mean is the issue here.