How can I make Json.NET serializer to serialize instance into array of objects?
Basically I need something like this:
[
{
"name":"Page1.html",
"size":1,
"outlinks":[
"Page2.html",
"Page3.html",
"Page4.html"
]
},
{
"name":"Page2.html",
"size":2,
"outlinks":[
"Page3.html"
]
},
{
"name":"Page3.html",
"size":3,
"outlinks":[
"Page1.html",
"Page2.html",
"Page3.html",
"Page4.html"
]
},
{
"name":"Page4.html",
"size":4,
"outlinks":[]
}
]
with:
Dictionary<string, string[]> UrlsCollection = new Dictionary<string, string[]>();
List<string> OutLinks = new List<string>();
OutLinks.Add("Page2.html");
OutLinks.Add("Page3.html");
OutLinks.Add("Page4.html");
UrlsCollection.Add("Page1.html", OutLinks.ToArray());
OutLinks.Clear();
OutLinks.Add("Page3.html");
UrlsCollection.Add("Page2.html", OutLinks.ToArray());
OutLinks.Clear();
OutLinks.Add("Page1.html");
OutLinks.Add("Page2.html");
OutLinks.Add("Page3.html");
OutLinks.Add("Page4.html");
UrlsCollection.Add("Page3.html", OutLinks.ToArray());
OutLinks.Clear();
UrlsCollection.Add("Page4.html", OutLinks.ToArray());
OutLinks.Clear();
string jsonUrlsCollection = JsonConvert.SerializeObject(UrlsCollection.ToList(), Formatting.Indented);
I get:
[
{
"Key": "Page1.html",
"Value": [
"Page2.html",
"Page3.html",
"Page4.html"
]
},
{
"Key": "Page2.html",
"Value": [
"Page3.html"
]
},
{
"Key": "Page3.html",
"Value": [
"Page1.html",
"Page2.html",
"Page3.html",
"Page4.html"
]
},
{
"Key": "Page4.html",
"Value": []
}
]
There must be a way/something to get a simple JSON Object?
Modifying the solution to reflect Deblaton Jean-Philippe's suggestion in the comments.
public class UrlDef
{
public UrlDef() { outlinks = new List<string>(); }
public string name { get; set; }
public int size { get; set; }
public List<string> outlinks { get; set; }
}
List<UrlDef> UrlsCollection = new List<UrlDef>();
UrlDef urldef;
urldef = new UrlDef();
urldef.name = "Page1.html";
urldef.size = 1;
urldef.outlinks.Add("Page2.html");
urldef.outlinks.Add("Page3.html");
urldef.outlinks.Add("Page4.html");
UrlsCollection.Add(urldef);
urldef = new UrlDef();
urldef.name = "Page2.html";
urldef.size = 2;
urldef.outlinks.Add("Page3.html");
UrlsCollection.Add(urldef);
urldef = new UrlDef();
urldef.name = "Page3.html";
urldef.size = 3;
urldef.outlinks.Add("Page1.html");
urldef.outlinks.Add("Page2.html");
urldef.outlinks.Add("Page3.html");
urldef.outlinks.Add("Page4.html");
UrlsCollection.Add(urldef);
urldef = new UrlDef();
urldef.name = "Page4.html";
urldef.size = 4;
UrlsCollection.Add(urldef);
string jsonUrlsCollection = JsonConvert.SerializeObject(UrlsCollection, Formatting.Indented);
You need to serialize a list of this object
public class Url
{
public string name { get; set; }
public int size { get; set; }
public List<string> outlinks { get; set; }
}
For this answer, I used a website I often use when I know what I expect from JS, but I'm not sure of what I need to feed into the CS : http://json2csharp.com/
Related
I would like my output JSON to contain a simple array shown below
{
"attributes":[
{
"trait_type": "Background",
"value": "Green"
},
{
"trait_type": "Body",
"value": "Body_1"
},
{
"trait_type": "Outfit",
"value": "Beach_Singlet"
},
{
"display_type":"date",
"trait_type":"birthday",
"value":869270400
}
]
}
Notice how the last item is different from the previous items in the array. The variable named "value" is also an integer as compared to the previous entries as strings.
How do I go about in order to be able to output my JSON as shown above? I have tried creating a class that can store all the information, but I cannot reuse the name "value" for both an int and string declaration, and also do not wish to show the variables if their value is null
(Example shown below)
{
"attributes": [
{
"display_type": "",
"trait_type": "Background",
"value": "Green"
},
{
"display_type": "",
"trait_type": "Body",
"value": "Body_1"
},
{
"display_type": "",
"trait_type": "Outfit",
"value": "Beach_Singlet"
},
{
"display_type": "date",
"trait_type": "birthday",
"value": 869270400
}
]
}
You can use object type.
using Newtonsoft.Json;
var list = new AttributeList
{
attributes = new []{
new Attribute
{
trait_type = "Background",
value = "green"
},
new Attribute
{
display_type = "date",
trait_type = "birthday",
value = 869270400
}
}
};
var json = JsonConvert.SerializeObject(list, Formatting.Indented);
Console.WriteLine(json);
public class Attribute
{
public object value { get; set; }
public string trait_type { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string display_type { get; set; }
}
public class AttributeList
{
public Attribute[] attributes { get; set; }
}
Output:
{
"attributes": [
{
"value": "green",
"trait_type": "Background"
},
{
"value": 869270400,
"trait_type": "birthday",
"display_type": "date"
}
]
}
try this
var attributes=new List<Attribute>{
new AttributeString{
trait_type="Background",
value="green"
},
new AttributeInt{
display_type ="date",
trait_type="birthday",
value=869270400
}
};
var jsonSerializerSettings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.Objects,
NullValueHandling=NullValueHandling.Ignore,
Formatting=Newtonsoft.Json.Formatting.Indented
};
var json = JsonConvert.SerializeObject(attributes,jsonSerializerSettings);
classes
public class Attribute
{
public string trait_type { get; set; }
public string display_type { get; set; }
}
public class AttributeString:Attribute
{
public string value { get; set; }
}
public class AttributeInt:Attribute
{
public int value { get; set; }
}
public class AttributeList
{
public List<Attribute> attributes { get; set; }
}
I have Json where i have 2 objects. I would like to know how to change value in my json, when other value is looking for. For example i would like to change "speciality" to "Warrior" for Person who's "Name" is Harry.
It's my Json
{
"Person": [
{
"Speciality": "Archer",
"Id": 432742,
"Name": "Charlie",
"Surname": "Evans",
"Items": [
"Bow",
"Arrow",
]
},
{
"Speciality": "Soldier",
"Id": 432534,
"Name": "Harry",
"Surname": "Thomas",
"Items": [
"Gun",
"Knife",
]
}
],
"Monster": [
{
"Name": "Papua",
"Skills": [
"Jump",
"SlowWalk",
]
},
{
"Name": "Geot",
"Skills": [
"Run",
"Push",
]
}
]
}
My classes
public class Person
{
public string Speciality { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public List<string> Items { get; set; }
}
public class Monster
{
public string Name { get; set; }
public List<string> Skills { get; set; }
}
public class Root
{
public List<Person> People { get; set; }
public List<Monster> Monsters { get; set; }
}
I tried something like this:
var result = JsonSerializer.Deserialize<Root>(jsonfile)
for (int i = 0; i < result.People.Count; ++i)
{
result.Where(w => w.Person.Name == "Harry").ToList().ForEach(s => s.Person.Speciality = "Warrior");
}
Thanks in advance for some help.
Your can use foreach loop
var result = JsonSerializer.Deserialize<Root>(jsonfile);
foreach (var person in result.Person)
{
if(person.Name == "Harry"){
person.Speciality = "";
}
}
I have stored JSON data in a string and by using the JObject, I am trying to get values from JSON data. I am just not able to figure out that what is the underlying issue with my code because I am not able to get data from the JSON object. A snippet of my code is attached below. If some can help me out to figure out the issue it will be immensely appreciated.
String text;
try {
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
JObject jObject = JObject.Parse(text);
string haha = (string)jObject["value/segments/requests/count/sum"];
ViewBag.gotstring = haha;
}
System.Diagnostics.Debug.WriteLine(text);
} catch(Exception e) {
System.Diagnostics.Debug.WriteLine(url);
System.Diagnostics.Debug.WriteLine(e.ToString()); }
return View();
Here is the JSON:
{
"value": {
"start": "2018-08-12T04:44:38.941Z",
"end": "2018-08-12T16:44:38.941Z",
"interval": "PT30M",
"segments": [
{
"start": "2018-08-12T14:00:00Z",
"end": "2018-08-12T14:30:00Z",
"segments": [
{
"requests/count": {
"sum": 2
},
"request/name": "GET Home/Index"
},
{
"requests/count": {
"sum": 1
},
"request/name": "GET Home/About"
},
{
"requests/count": {
"sum": 1
},
"request/name": "GET Home/Contact"
}
]
},
{
"start": "2018-08-12T14:30:00Z",
"end": "2018-08-12T15:00:00Z",
"segments": [
{
"requests/count": {
"sum": 2
},
"request/name": "GET Account/Register"
},
{
"requests/count": {
"sum": 1
},
"request/name": "GET Account/Login"
}
]
},
{
"start": "2018-08-12T15:30:00Z",
"end": "2018-08-12T16:00:00Z",
"segments": [
{
"requests/count": {
"sum": 8
},
"request/name": "GET Home/Index"
},
{
"requests/count": {
"sum": 8
},
"request/name": "GET Home/About"
}
]
}
]
}
}
jObject does not work this way. It returns dictionary that you can query by key, but keys are single level. I.e. you'll be able to get some data like this:
var haha = jObject["value"]["segments"];
But beyond that it gets very complex. You'll be much better off defining a C# class that represents your JSON and serialise into that. A simple `Edit=>Paste Special => JSON as Class" in Visual Studio gives this:
public class Rootobject
{
public Value value { get; set; }
}
public class Value
{
public DateTime start { get; set; }
public DateTime end { get; set; }
public string interval { get; set; }
public Segment[] segments { get; set; }
}
public class Segment
{
public DateTime start { get; set; }
public DateTime end { get; set; }
public Segment1[] segments { get; set; }
}
public class Segment1
{
[JsonProperty("requests/count")]
public RequestsCount requestscount { get; set; }
[JsonProperty("request/name")]
public string requestname { get; set; }
}
public class RequestsCount
{
public int sum { get; set; }
}
and then deserialise like this:
var serialised = JsonConvert.DeserializeObject<Rootobject>(json);
var haha = serialised.value.segments.FirstOrDefault().segments.FirstOrDefault().requestscount.sum;
And here is a working sample: https://dotnetfiddle.net/CZgMNE
Can you try:
EDIT: seems like segments is an array, this will get you the sum for first segment only
string haha = (string)jObject["value"]["segments"][0]["segments"]["requests/count"]["sum"];
public static string DeserializeNames()
{
// Json I am passing for the deserialization.
JsonStream= "{
"head": {
"Rows": [
"test 1",
[
[
{
"#Key": "Domain",
"#value": "LocalHost"
},
{
"#Key": "Cookie name(s)",
"#value": "Google"
},
{
"#Key": "Purpose",
"#value": "Test"
},
{
"#Key": "lifetime",
"#value": "test"
}
]
]
]
}
}"
//deserialize JSON from file
JavaScriptSerializer serializer = new JavaScriptSerializer();
var cookieList = serializer.Deserialize<List<Cookie>>(JsonStream).ToList();
}
//Class descriptions
//I have created below classes for the deserialization. Records are not deserialized i am getting zero record count.
public class Categorization
{
public string categorizationName { get; set; }
public List<object> KeyValue{ get; set; }
}
public class Head
{
public IList<Categorization> Rows { get; set; }
}
public class Cookie
{
public Head head { get; set; }
}
Also created below set of the classes and tried the deserialization, Still no luck
public class Head
{
public List<object> Rows { get; set; }
}
public class Cookie
{
public Head head { get; set; }
}
I am getting count as 0 i am not able to fetch any record.
Please help !!
I have modified the Json as below and stored in in the file "test.json" :
{
"head": {
"TestRows": [
[
{
"Key": "Domain",
"value": "Google"
},
{
"Key": "Cookie",
"value": "Test"
},
{
"Key": "Use for",
"value": "Test."
},
{
"Key": "Expire Time",
"value": "1 hour"
}
]
]
}
}
And created below set of classes :
public class Head
{
public IList<List<Dictionary<string, object>>> TestRows{ get; set; }
}
public class Cookie
{
public Head Head { get; set; }
}
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var path= Path.Combine(baseDirectory, "test.json");
//deserialize JSON from file
string JsonStream = System.IO.File.ReadAllText(path, Encoding.Default);
var DeserializedCookieList = JsonConvert.DeserializeObject<Cookie>(JsonStream);
Deserialization is working properly.
How do I create a JSON array using Newtonsoft.JSON (json.net) from this json string
[
{
"Cells": {
"results": [
{
"Key": "Title",
"Value": "hello",
"ValueType": "Edm.String"
},
{
"Key": "Size",
"Value": "54549",
"ValueType": "Edm.Int64"
},
{
"Key": "Path",
"Value": "http://somesite/a/hello.pptx",
"ValueType": "Edm.String"
},
{
"Key": "Summary",
"Value": "Some summary <ddd/> interesting reading <ddd/> nice book <ddd/> ",
"ValueType": "Edm.String"
},
{
"Key": "Name",
"Value": "http://somesite",
"ValueType": "Edm.String"
}
]
}
},
{
"Cells": {
"results": [
{
"Key": "Title",
"Value": "hi joe",
"ValueType": "Edm.String"
},
{
"Key": "Size",
"Value": "41234",
"ValueType": "Edm.Int64"
},
{
"Key": "Path",
"Value": "http://someothersite/interesting/hi.pptx",
"ValueType": "Edm.String"
},
{
"Key": "Summary",
"Value": "Some summary <ddd/> interesting reading <ddd/> nice book <ddd/> ",
"ValueType": "Edm.String"
},
{
"Key": "Name",
"Value": "http://somesite",
"ValueType": "Edm.String"
}
]
}
}
]
json2csharp gives me following classes for this structure
public class Result
{
public string Key { get; set; }
public string Value { get; set; }
public string ValueType { get; set; }
}
public class Cells
{
public List<Result> results { get; set; }
}
public class RootObject
{
public Cells Cells { get; set; }
}
How do I use these classes to create json array?
UPDATE AND SOLUTION
this will work
static void Main(string[] args)
{
RootObject ro = new RootObject();
Cells cs = new Cells();
cs.results = new List<Result>();
Result rt = new Result();
rt.Key = "Title";
rt.Value = "hello";
rt.ValueType = "Edm.String";
cs.results.Add(rt);
Result rs = new Result();
rs.Key = "Size";
rs.Value = "3223";
rs.ValueType = "Edm.Int64";
cs.results.Add(rs);
ro.Cells = cs;
string json = JsonConvert.SerializeObject(ro);
}
this will work
static void Main(string[] args)
{
RootObject ro = new RootObject();
Cells cs = new Cells();
cs.results = new List<Result>();
Result rt = new Result();
rt.Key = "Title";
rt.Value = "hello";
rt.ValueType = "Edm.String";
cs.results.Add(rt);
Result rs = new Result();
rs.Key = "Size";
rs.Value = "3223";
rs.ValueType = "Edm.Int64";
cs.results.Add(rs);
ro.Cells = cs;
string json = JsonConvert.SerializeObject(ro);
}
You're looking for the function DeserializeObject<T>:
var json = ""; // string up above in your code
var jObect = JsonConvert.DeserializeObject<RootObject>(json);
// Use
var cells = jObject.Cells;
var result1 = cells.results.FirstOrDefault();
Given an example of a POCO below:
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
This can be achieved by deserializing your JSON string show below:
string json = #"{
'Email': 'james#example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);
Reference Newtonsoft's documentation below:
http://www.newtonsoft.com/json/help/html/DeserializeObject.htm
If you want the string representation of an object, especially a json object, the most relevant is .ToString ().
But, it could fail for other reasons ...