Defining a dictionary in a C# class - c#

I have a .json file which i want to read in C#.
The Json File looks like this:
{"SN0124":{
"category1": 0,
"output": {
"ABC": [],
"DEF": 0,
"GHI": "ABDEF"
},
"category2": 0,
"category3": 0
},
"SN0123":{
"category1": 0,
"output": {
"ABC": ["N1", "N2"],
"DEF": 0,
"GHI": "ABDEF"
},
"category2": 0,
"category3": 0
}
Initially the output field was absent and my custom class for reading the Json file is as follows:
namespace Server.Models
{
public class Pets
{
public string category1 { get; set; }
public string category2 { get; set; }
public string category3 { get; set; }
}
}
The output was recently added and I am not sure how to include that dictionary in the class file so that I can read the json file. Any help will be greatly appreciated.
thanks!

This should work fine. I have basically created a new class called Output that contains the expected JSON fields. I have also edited the type of the category fields to int.
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string JSONInput = #"{""SN0124"": {
""category1"": 0,
""output"": {
""ABC"": [],
""DEF"": 0,
""GHI"": ""ABDEF""
},
""category2"": 0,
""category3"": 0
},
""SN0123"": {
""category1"": 0,
""output"": {
""ABC"": [""N1"", ""N2""],
""DEF"": 0,
""GHI"": ""ABDEF""
},
""category2"": 0,
""category3"": 0
}}";
Dictionary<string, Pets> deserializedProduct = JsonConvert.DeserializeObject<Dictionary<string, Pets>>(JSONInput);
Console.ReadKey();
}
}
public class Output
{
public string[] ABC { get; set; }
public int DEF { get; set; }
public string GHI { get; set; }
}
public class Pets
{
public int category1 { get; set; }
public Output output { get; set; }
public int category2 { get; set; }
public int category3 { get; set; }
}
}

I'm not sure I fully understand what you mean. If I understand right you're trying to hold the values from output in a dictionary?
You could do something like:
var output = new Dictionary<string, string[]>();
But it might be simpler to create a custom class to hold that data structures.

Related

How to get a specific field from json object by key:value?

I'm trying to save my data using json. I don't know how to get specific object group from a set of json objects.
[
{
"dateinformation": "2021-10-05:23:01",
"id": 1,
"MoveCount": 3,
"StartPoint": 2322,
"TotalDist": 2331,
"SafeDist": 21332,
"Feed": 2332,
"EndPoint":23245,
"Count":1221,
},
{
"dateinformation": "2021-10-05:26:01",
"id": 2,
"MoveCount": 3,
"StartPoint": 2322,
"TotalDist": 2331,
"SafeDist": 21332,
"Feed": 2332,
"EndPoint":23245,
"Count":1221,
},
{
"dateinformation": "2021-10-55:03:01",
"id": 3,
"MoveCount": 3,
"StartPoint": 2322,
"TotalDist": 2331,
"SafeDist": 21332,
"Feed": 2332,
"EndPoint":23245,
"Count":1221,
}]
is it possible to get/delete a specific object from a bundle of json object by its "id" value?
Do like that
NameSpace will include:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
Here you can replace your id by specificId
List<Root> myDeserializedClass = JsonConvert.DeserializeObject<List<Root>>(myJsonResponse); // myJsonResponse is My Source Json
int specificId = 123; // my dynamic
var specficObject = myDeserializedClass.Where(x => x.id == specificId);
Class for Deserialize your JSON response:
public class Root
{
public string dateinformation { get; set; }
public int id { get; set; }
public int MoveCount { get; set; }
public int StartPoint { get; set; }
public int TotalDist { get; set; }
public int SafeDist { get; set; }
public int Feed { get; set; }
public int EndPoint { get; set; }
public int Count { get; set; }
}
Also, I have noticed your JSON last column comma in last that should not be like that "Count" : 1221,

Desalinizing JSON Object Contains List of Objects Returns Null for the nested object

This is my first attempt of working with JSON deserialization. I have read many of the posts in Stackoverflow, non of the suggested solutions could match my issue, so my apology in advance. I have created the following objects:
public class Item
{
public int ID { get; set; }
public int LSum { get; set; }
public int YSum { get; set; }
public int TSum { get; set; }
public int NSum { get; set; }
public int MemberId { get; set; }
}
public class Something
{
public int Id { get; set; }
public string Phone { get; set; }
public bool ExistingMember { get; set; }
public IList<Item> Item { get; set; }
}
And when deserialize the JSON it looks like following:
The follwoing JSON what I expect it to be:
{
"Id":62,
"Phone":"07",
"ExistingMember":true,
"Item":[
{
"ID":42,
"LSum":0,
"YSum":0,
"TSum":0,
"NSum":0,
"MemberId":12
}
]
}
However the following method it
some= JsonConvert.DeserializeObject<something>(someResponse);
It prints the json like the following:
The following JSON is what is "someResponse" return,
{
"Id":62,
"Phone":"07",
"ExistingMember":true,
"Item":null
}
What am I missing that the item list is return null?
If you want to deserialize json string which in your case is someResponse variable, then you are doing it right.
To check your code I created a JSON file with a file.json name and put the following on it:
{
"Id": 62,
"Phone": "07",
"ExistingMember": true,
"Item": [
{
"ID": 42,
"LSum": 0,
"YSum": 0,
"TSum": 0,
"NSum": 0,
"MemberId": 12
}
]
}
Then below lines of code take the content of JSON file (which in your case is the content of someResponse) and deserialize it into c# object of Something type:
string jsonFilePath = #"C:\test\file.json";
var some = JsonConvert.DeserializeObject<Something>(File.ReadAllText(jsonFilePath));
Then print the ID property of each element of Item list:
foreach(var item in some.Item)
{
if (item != null)
{
Console.WriteLine($"item ID = {item.ID}");
}
}
The output:
item ID = 42
So, it is quite possible that someResponse just does not have an Item and looks like this:
{
"Id": 62,
"Phone": "07",
"ExistingMember": true
}
UPDATE:
Also I tried like this:
var someResponse = #"{
'Id': 62,
'Phone': '07',
'ExistingMember': true,
'Item':[
{
'ID': 42,
'LSum': 0,
'YSum': 0,
'TSum': 0,
'NSum': 0,
'MemberId': 12
}
]
}
";
var some = JsonConvert.DeserializeObject<Something>(someResponse);
And some has a Item list with 1 element

Deserialize JSON in C# to array

I'm having trouble doing deserialize a certain json I am collecting a website.
{
"query": {
"search": [
{
"ns": 0,
"title": "test",
"snippet": "test"
},
{
"ns": 0,
"title": "test2",
"snippet": "test2"
},
{
"ns": 0,
"title": "test3",
"snippet": "test3"
},
{
"ns": 0,
"title": "test4",
"snippet": "test4"
}
]
}
}
This is the class that I'm trying to deserialize into:
private void DesURL_Click(object sender, RoutedEventArgs e)
{
string url = #"https://pt.wikipedia.org/w/api.php.....";
var json = new WebClient().DownloadString(url);
var listaURL = JsonConvert.DeserializeObject<List<Query>>(json);
}
when trying to run the code of an error that this json should be deserialized into an array. Ai trying utiilizar JArray the method I need to do the deserialize before you can turn into array.
The goal is to convert the title and snippet to string in order to extract information from it.
Pro tip for you: Select your JSON and copy it to the clipboard. Now go to Visual Studio and on the Edit menu, Paste Special and then Paste JSON as Classes. that will give you this:
public class Rootobject
{
public Query query { get; set; }
}
public class Query
{
public Search[] search { get; set; }
}
public class Search
{
public int ns { get; set; }
public string title { get; set; }
public string snippet { get; set; }
}
And now you can deserialise like this:
var listaURL = JsonConvert.DeserializeObject<Rootobject>(json);
You need the following classes:
public class Rootobject
{
public Query query { get; set; }
}
public class Query
{
public Search[] search { get; set; }
}
public class Search
{
public int ns { get; set; }
public string title { get; set; }
public string snippet { get; set; }
}
Then you can deserialize like this:
var listUrl = JsonConvert.DeserializeObject<Rootobject>(json);
Your JSON is not an array. It contains a query object with a search property that has an array value.
So your class has to look something like this
public class ResponseDto {
public QueryDto Query {get; set;}
}
public class QueryDto {
public IEnumerable<Query> Search {get; set;}
}
var data = JsonConvert.DeserializeObject<QueryDto>(json);
var list = data.Query.Search.ToList();

Read JSON string as key value

I have following json:
{
"serverTime": "2013-08-12 02:45:55,558",
"data": [
{
"key1": 1,
"key2": {},
"key3": {
"key4": [
""
],
"key5": "test2"
},
"key7": 0
},
{
"key8": 1,
"key9": {},
"key10": {
"key4": [
""
],
"key9": "test2"
},
"key11": 0
}
]
}
I want to get values as key value pair. Something like:
jsonObject[data][0]
should give first item of the data array.
I am using JSONFx.net. But it gives strongly typed objects. I do not want that.
Is there any way to parse JSON as key value as I mentioned earlier?
Thanks
Try this:
using System;
using System.IO;
using Newtonsoft.Json;
class Program
{
static void Main(string[] args)
{
var json = File.ReadAllText("input.txt");
var a = new { serverTime = "", data = new object[] { } };
var c = new JsonSerializer();
dynamic jsonObject = c.Deserialize(new StringReader(json), a.GetType());
Console.WriteLine(jsonObject.data[0]);
}
}
If you're not averse to using Json.NET, you can do this:
var jsonString = #"
{
""serverTime"": ""2013-08-12 02:45:55,558"",
""data"": [
{
""key1"": 1,
""key2"": {},
""key3"": {
""key4"": [
""""
],
""key5"": ""test2""
},
""key7"": 0
},
{
""key8"": 1,
""key9"": {},
""key10"": {
""key4"": [
""""
],
""key9"": ""test2""
},
""key11"": 0
}
]
}";
var jsonResult = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);
var firstItem = jsonResult["data"][0];
firstItem would be an array of the first item in the data array:
Hope this helps.
First create classes to parse string
public class Key2
{
}
public class Key3
{
public List<string> key4 { get; set; }
public string key5 { get; set; }
}
public class Key9
{
}
public class Key10
{
public List<string> key4 { get; set; }
public string key9 { get; set; }
}
public class Datum
{
public int key1 { get; set; }
public Key2 key2 { get; set; }
public Key3 key3 { get; set; }
public int key7 { get; set; }
public int? key8 { get; set; }
public Key9 key9 { get; set; }
public Key10 key10 { get; set; }
public int? key11 { get; set; }
}
public class RootObject
{
public string serverTime { get; set; }
public List<Datum> data { get; set; }
}
add reference of Newtonsoft.Json.dll
RootObject obj = JsonConvert.DeserializeObject<RootObject>(jsonData);
then you can access values .
If you want to do this without third party libraries then do:
I would use the following code:
var deserializer = new JavaScriptSerializer();
var someObject = deserializer.DeserializeObject(json);
string serverTime = someObject["serverTime"].ToString();
Dictionary<string, int> data = someObject["data"] as Dictionary<string, int>;
Give it a go.
Edit: You may need to change the last line to:
Dictionary<string, int?> data = someObject["data"] as Dictionary<string, int?>;

deserialize the following json response in c#

Can someone please help me deserialize the following JSON string in C#:
{"legend_size": 1,
"data": {"series": ["2013-02-05", "2013-02-06", "2013-02-07", "2013-02-08", "2013-02-09", "2013-02-10", "2013-02-11", "2013-02-12", "2013-02-13", "2013-02-14"], "values":
{"CampaignHit": {"2013-02-14": 0, "2013-02-13": 0, "2013-02-12": 0, "2013-02-11": 0, "2013-02-10": 0, "2013-02-08": 11, "2013-02-05": 0, "2013-02-07": 14, "2013-02-06": 0, "2013-02-09": 0}}}}
I having problems with the CampaignHit part. I am not able to deserialize it.
Here are the classes I created:
public class ExportedData
{
public string legend_size { get; set; }
public Data data { get; set; }
}
public class Data
{
public string[] series { get; set; }
public Values values { get; set; }
}
public class Values
{
public CampaignHit CampaignHit { get; set; }
}
public class CampaignHit
{
public CampaignData[] data { get; set; }
}
public class CampaignData
{
public object first { get; set; }
public object second { get; set; }
}
Here is the code to deserialize json:
var result = JsonConvert.DeserializeObject<ExportedData>(jsonResponse);
The data part is null. How do I change the CampaignHit class so that data is not null after deserialization.
A solution using Newtonsoft.Json :
JObject jObject = JObject.Parse(#"{
'legend_size': 1,
'data': {
'series': [
'2013-02-05', '2013-02-06', '2013-02-07', '2013-02-08', '2013-02-09', '2013-02-10', '2013-02-11', '2013-02-12', '2013-02-13', '2013-02-14'
],
'values': {
'CampaignHit': {
'2013-02-14': 0,
'2013-02-13': 0,
'2013-02-12': 0,
'2013-02-11': 0,
'2013-02-10': 0,
'2013-02-08': 11,
'2013-02-05': 0,
'2013-02-07': 14,
'2013-02-06': 0,
'2013-02-09': 0
}
}
}
}");
var campaignHit = jObject["data"]["values"]["CampaignHit"];
Dictionary<string,int> campaignHitDic = new Dictionary<string,int>();
foreach(JProperty c in campaignHit){
campaignHitDic.Add(c.Name,(int)c.Value);
}

Categories

Resources