I have classes like these:
class MyDate
{
int year, month, day;
}
class Lad
{
string firstName;
string lastName;
MyDate dateOfBirth;
}
And I would like to turn a Lad object into a JSON string like this:
{
"firstName":"Markoff",
"lastName":"Chaney",
"dateOfBirth":
{
"year":"1901",
"month":"4",
"day":"30"
}
}
(Without the formatting). I found this link, but it uses a namespace that's not in .NET 4. I also heard about JSON.NET, but their site seems to be down at the moment, and I'm not keen on using external DLL files.
Are there other options besides manually creating a JSON string writer?
Since we all love one-liners
... this one depends on the Newtonsoft NuGet package, which is popular and better than the default serializer.
Newtonsoft.Json.JsonConvert.SerializeObject(new {foo = "bar"})
Documentation: Serializing and Deserializing JSON
Please Note
Microsoft recommends that you DO NOT USE JavaScriptSerializer
See the header of the documentation page:
For .NET Framework 4.7.2 and later versions, use the APIs in the System.Text.Json namespace for serialization and deserialization. For earlier versions of .NET Framework, use Newtonsoft.Json.
Original answer:
You could use the JavaScriptSerializer class (add reference to System.Web.Extensions):
using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);
A full example:
using System;
using System.Web.Script.Serialization;
public class MyDate
{
public int year;
public int month;
public int day;
}
public class Lad
{
public string firstName;
public string lastName;
public MyDate dateOfBirth;
}
class Program
{
static void Main()
{
var obj = new Lad
{
firstName = "Markoff",
lastName = "Chaney",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var json = new JavaScriptSerializer().Serialize(obj);
Console.WriteLine(json);
}
}
Use Json.Net library, you can download it from Nuget Packet Manager.
Serializing to Json String:
var obj = new Lad
{
firstName = "Markoff",
lastName = "Chaney",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
Deserializing to Object:
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Lad>(jsonString );
Use the DataContractJsonSerializer class: MSDN1, MSDN2.
My example: HERE.
It can also safely deserialize objects from a JSON string, unlike JavaScriptSerializer. But personally I still prefer Json.NET.
A new JSON serializer is available in the System.Text.Json namespace. It's included in the .NET Core 3.0 shared framework and is in a NuGet package for projects that target .NET Standard or .NET Framework or .NET Core 2.x.
Example code:
using System;
using System.Text.Json;
public class MyDate
{
public int year { get; set; }
public int month { get; set; }
public int day { get; set; }
}
public class Lad
{
public string FirstName { get; set; }
public string LastName { get; set; }
public MyDate DateOfBirth { get; set; }
}
class Program
{
static void Main()
{
var lad = new Lad
{
FirstName = "Markoff",
LastName = "Chaney",
DateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var json = JsonSerializer.Serialize(lad);
Console.WriteLine(json);
}
}
In this example the classes to be serialized have properties rather than fields; the System.Text.Json serializer currently doesn't serialize fields.
Documentation:
System.Text.Json overview
How to use System.Text.Json
You can achieve this by using Newtonsoft.json. Install Newtonsoft.json from NuGet. And then:
using Newtonsoft.Json;
var jsonString = JsonConvert.SerializeObject(obj);
Wooou! Really better using a JSON framework :)
Here is my example using Json.NET (http://james.newtonking.com/json):
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.IO;
namespace com.blogspot.jeanjmichel.jsontest.model
{
public class Contact
{
private Int64 id;
private String name;
List<Address> addresses;
public Int64 Id
{
set { this.id = value; }
get { return this.id; }
}
public String Name
{
set { this.name = value; }
get { return this.name; }
}
public List<Address> Addresses
{
set { this.addresses = value; }
get { return this.addresses; }
}
public String ToJSONRepresentation()
{
StringBuilder sb = new StringBuilder();
JsonWriter jw = new JsonTextWriter(new StringWriter(sb));
jw.Formatting = Formatting.Indented;
jw.WriteStartObject();
jw.WritePropertyName("id");
jw.WriteValue(this.Id);
jw.WritePropertyName("name");
jw.WriteValue(this.Name);
jw.WritePropertyName("addresses");
jw.WriteStartArray();
int i;
i = 0;
for (i = 0; i < addresses.Count; i++)
{
jw.WriteStartObject();
jw.WritePropertyName("id");
jw.WriteValue(addresses[i].Id);
jw.WritePropertyName("streetAddress");
jw.WriteValue(addresses[i].StreetAddress);
jw.WritePropertyName("complement");
jw.WriteValue(addresses[i].Complement);
jw.WritePropertyName("city");
jw.WriteValue(addresses[i].City);
jw.WritePropertyName("province");
jw.WriteValue(addresses[i].Province);
jw.WritePropertyName("country");
jw.WriteValue(addresses[i].Country);
jw.WritePropertyName("postalCode");
jw.WriteValue(addresses[i].PostalCode);
jw.WriteEndObject();
}
jw.WriteEndArray();
jw.WriteEndObject();
return sb.ToString();
}
public Contact()
{
}
public Contact(Int64 id, String personName, List<Address> addresses)
{
this.id = id;
this.name = personName;
this.addresses = addresses;
}
public Contact(String JSONRepresentation)
{
//To do
}
}
}
The test:
using System;
using System.Collections.Generic;
using com.blogspot.jeanjmichel.jsontest.model;
namespace com.blogspot.jeanjmichel.jsontest.main
{
public class Program
{
static void Main(string[] args)
{
List<Address> addresses = new List<Address>();
addresses.Add(new Address(1, "Rua Dr. Fernandes Coelho, 85", "15º andar", "São Paulo", "São Paulo", "Brazil", "05423040"));
addresses.Add(new Address(2, "Avenida Senador Teotônio Vilela, 241", null, "São Paulo", "São Paulo", "Brazil", null));
Contact contact = new Contact(1, "Ayrton Senna", addresses);
Console.WriteLine(contact.ToJSONRepresentation());
Console.ReadKey();
}
}
}
The result:
{
"id": 1,
"name": "Ayrton Senna",
"addresses": [
{
"id": 1,
"streetAddress": "Rua Dr. Fernandes Coelho, 85",
"complement": "15º andar",
"city": "São Paulo",
"province": "São Paulo",
"country": "Brazil",
"postalCode": "05423040"
},
{
"id": 2,
"streetAddress": "Avenida Senador Teotônio Vilela, 241",
"complement": null,
"city": "São Paulo",
"province": "São Paulo",
"country": "Brazil",
"postalCode": null
}
]
}
Now I will implement the constructor method that will receives a JSON string and populates the class' fields.
If they are not very big, what's probably your case export it as JSON.
Also this makes it portable among all platforms.
using Newtonsoft.Json;
[TestMethod]
public void ExportJson()
{
double[,] b = new double[,]
{
{ 110, 120, 130, 140, 150 },
{1110, 1120, 1130, 1140, 1150},
{1000, 1, 5, 9, 1000},
{1110, 2, 6, 10, 1110},
{1220, 3, 7, 11, 1220},
{1330, 4, 8, 12, 1330}
};
string jsonStr = JsonConvert.SerializeObject(b);
Console.WriteLine(jsonStr);
string path = "X:\\Programming\\workspaceEclipse\\PyTutorials\\src\\tensorflow_tutorials\\export.txt";
File.WriteAllText(path, jsonStr);
}
If you are in an ASP.NET MVC web controller it's as simple as:
string ladAsJson = Json(Lad);
Can't believe no one has mentioned this.
I would vote for ServiceStack's JSON Serializer:
using ServiceStack;
string jsonString = new { FirstName = "James" }.ToJson();
It is also the fastest JSON serializer available for .NET:
http://www.servicestack.net/benchmarks/
Another solution using built-in System.Text.Json (.NET Core 3.0+) where an object is self-sufficient and doesn't expose all possible fields:
A passing test:
using NUnit.Framework;
namespace Intech.UnitTests
{
public class UserTests
{
[Test]
public void ConvertsItselfToJson()
{
var userName = "John";
var user = new User(userName);
var actual = user.ToJson();
Assert.AreEqual($"{{\"Name\":\"{userName}\"}}", actual);
}
}
}
An implementation:
using System.Text.Json;
using System.Collections.Generic;
namespace Intech
{
public class User
{
private readonly string name;
public User(string name)
{
this.name = name;
}
public string ToJson()
{
var params = new Dictionary<string, string>{{"Name", name}};
return JsonSerializer.Serialize(params);
}
}
}
In your Lad model class, add an override to the ToString() method that returns a JSON string version of your Lad object.
Note: you will need to import System.Text.Json;
using System.Text.Json;
class MyDate
{
int year, month, day;
}
class Lad
{
public string firstName { get; set; };
public string lastName { get; set; };
public MyDate dateOfBirth { get; set; };
public override string ToString() => JsonSerializer.Serialize<Lad>(this);
}
It is as easy as this (it works for dynamic objects as well (type object)):
string json = new
System.Web.Script.Serialization.JavaScriptSerializer().Serialize(MYOBJECT);
Here is another solution using Cinchoo ETL - an open source library
public class MyDate
{
public int year { get; set; }
public int month { get; set; }
public int day { get; set; }
}
public class Lad
{
public string firstName { get; set; }
public string lastName { get; set; }
public MyDate dateOfBirth { get; set; }
}
static void ToJsonString()
{
var obj = new Lad
{
firstName = "Tom",
lastName = "Smith",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var json = ChoJSONWriter.Serialize<Lad>(obj);
Console.WriteLine(json);
}
Output:
{
"firstName": "Tom",
"lastName": "Smith",
"dateOfBirth": {
"year": 1901,
"month": 4,
"day": 30
}
}
Disclaimer: I'm the author of this library.
Serializer
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite, new JsonSerializerSettings
{
Formatting = Formatting.Indented,
});
using (var writer = new StreamWriter(filePath, append))
{
writer.Write(contentsToWriteToFile);
}
}
Object
namespace MyConfig
{
public class AppConfigurationSettings
{
public AppConfigurationSettings()
{
/* initialize the object if you want to output a new document
* for use as a template or default settings possibly when
* an app is started.
*/
if (AppSettings == null) { AppSettings=new AppSettings();}
}
public AppSettings AppSettings { get; set; }
}
public class AppSettings
{
public bool DebugMode { get; set; } = false;
}
}
Implementation
var jsonObject = new AppConfigurationSettings();
WriteToJsonFile<AppConfigurationSettings>(file.FullName, jsonObject);
Output
{
"AppSettings": {
"DebugMode": false
}
}
Related
I know its an array, but I am completely new to JSON and need help comprehending how this is structured, here is my attempt at extracting data:
String JSonString = readURL("//my URL is here");
JSONArray s = JSONArray.fromObject(JSonString);
JSONObject Data =(JSONObject)(s.getJSONObject(0));
System.out.println(Data.get("RecycleSiteUrl"));
I want to extract RecycleSiteUrl based on SiteId
My JSON data that I have goes like this :
[
{
"SiteId": 1,
"RecycleLogoUrl": "https://static-contrado.s3-eu-west- 1.amazonaws.com/cms/recyclecarelabel/d867c499-abc0-4ade-bc1a-f5011032c3e0132901511939451201.jpeg",
"RecycleSiteUrl": "bagsoflove.co.uk/recycling",
"Culture": "en-GB"
},
{
"SiteId": 10,
"RecycleLogoUrl": "https://static-contrado.s3-eu-west-1.amazonaws.com/cms/recyclecarelabel/95d28588-33e3-420c-8b24-4a8095c0f6ac132901511364264751.jpeg",
"RecycleSiteUrl": "contrado.co.uk/recycling",
"Culture": "en-GB"
}]
I dont really have a strong grasp of this stuff so all the help is appreciated.
you can try this, it doesn't need to create any classes
var jsonParsed=JArray.Parse(json);
var siteId=10;
var recycleSiteUrl = GetRecycleSiteUrl(jsonParsed,siteId); // contrado.co.uk/recycling
public string GetRecycleSiteUrl(JArray jArray, int siteId)
{
return jArray.Where(x=> (string) x["SiteId"] == siteId.ToString()).First()["RecycleSiteUrl"].ToString();
}
or using json path
string recycleSiteUrl= (string)jsonParsed
.SelectToken("$[?(#.SiteId=="+siteId.ToString()+")].RecycleSiteUrl");
using Newtonsoft.Json;
using System.Linq;
public void Method()
{
var yourSearchParameter = 10;
string jsonStr = readURL("//my URL is here");
var obj = JsonConvert.DeserializeObject<List<RecycleSite>>(jsonStr);
var siteUrl = obj.SingleOrDefault(q => q.SiteId == yourSearchParameter).RecycleSiteUrl;
/* Do something with the siteUrl */
}
public class RecycleSite
{
public int SiteId { get; set; }
public string RecycleLogoUrl { get; set; }
public string RecycleSiteUrl { get; set; }
public string Culture{ get; set; }
}
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
public Class Site
{
public string GetRecycleSiteUrl(int siteId, string jsonArray)
{
var siteInfos = JsonConvert.DeserializeObject<List<SiteInfo>>(jsonArray);
string recycleSiteUrl = siteInfos.FirstOrDefault(info => info.SiteId == siteId).RecycleSiteUrl;
return recycleSiteUrl;
}
}
public class SiteInfo
{
public int SiteId { get; set; }
public string RecycleLogoUrl { get; set; }
public string RecycleSiteUrl { get; set; }
public string Culture { get; set; }
}
You can create Site object and access GetRecycleSiteUrl method by passing respective parameter values.
I am wondering what is the difference between these two serializers. when setting accept header = application/xml. Am using Plain DTOs as return values, Which one is preferred? Also consumer of the api who request xml in response which should be used?
Am working on aspnet core web api 3.1, building restful apis. Any suggestions/redirects on the above query will be helpful.
The XmlSerializerOutputFormatter is an asp.net core outputformatter that uses the XmlSerializer internally, whereas the DataContractSerializerOutputFormatter uses the DataContractSerializer internally.
The DataContractSerializer is more flexible in configuration. For example it supports reference detection to prevent the serializer from recursively serializing items, which would normally cause an endless loop.
In my own projects, I prefer to use the DataContractSerializerOutputFormatter because it's able to cope with properties with private setter
public string Text { get; private set; }
Failing case
Dtos project
namespace DataContractSerializerPOC.Dtos
{
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// Fullname can only be set from this project
public string FullName { get; internal set; }
}
public class PersonService
{
public List<Person> GetPeople()
{
// Create a list of people to be serialized
var people = new List<Person>
{
new Person { Id = 1, FirstName = "John", LastName = "Doe" },
new Person { Id = 2, FirstName = "Jim", LastName = "Flix" },
new Person { Id = 3, FirstName = "Jack", LastName = "Splick" },
};
// Set the fullname from this project
// In some cases you may need to do this, instead of implementing a readonly property
foreach (var person in people)
person.FullName = $"{person.FirstName} {person.LastName}";
return people;
}
}
}
Console project
namespace DataContractSerializerPOC
{
class Program
{
static void Main(string[] args)
{
var personService = new PersonService();
var people = personService.GetPeople();
var writer = new StringWriter();
var serializer = new XmlSerializer(typeof(List<Person>));
serializer.Serialize(writer, people);
}
}
}
Result
Working case with DataContractSerializer
Dtos project
namespace DataContractSerializerPOC.Dtos
{
[DataContract]
public class Person
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
// Fullname can only be set from this project
[DataMember]
public string FullName { get; internal set; }
}
public class PersonService
{
...
}
}
Console project
namespace DataContractSerializerPOC
{
class Program
{
static void Main(string[] args)
{
var personService = new PersonService();
var people = personService.GetPeople();
var memoryStream = new MemoryStream();
var serializer = new DataContractSerializer(typeof(List<Person>));
serializer.WriteObject(memoryStream, people);
memoryStream.Seek(0, SeekOrigin.Begin);
var text = new StreamReader(memoryStream).ReadToEnd();
}
}
}
Result
So the DataContractSerializer is able to deal with properties with a private setter, whilst the XmlSerializer isn't.
How can i write a compatible c# code for this?
I know i can do projection like this:
var projection = Builders<BsonDocument>.Projection.Include("title");
But no idea how to project the last name to get the author's last name after a lookup aggregation
db.books.aggregate(
[
{
$project: {
title: 1,
lastName: "$author.lastName",
}
}
]
)
Try this one
var project = new BsonDocument
{
{
"$project",
new BsonDocument
{
{"title", 1},
{"lastName", "$author.lastName"},
}
}
};
var pipelineLast = new[] { project };
var resultLast = db.books.Aggregate<BsonDocument>(pipelineLast);
var matchingExamples = await resultLast.ToListAsync();
foreach (var example in matchingExamples)
{
// Display the result
}
assuming your author entity is embedded inside the book entity, here's a strongly typed solution. if your author is a referenced entity, let me know and i'll update my answer.
using MongoDB.Entities;
using System;
using System.Linq;
namespace StackOverflow
{
public class Program
{
public class Book : Entity
{
public string Title { get; set; }
public Author Author { get; set; }
}
public class Author
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
private static void Main(string[] args)
{
new DB("test");
(new Book
{
Title = "a book title goes here",
Author = new Author
{
FirstName = "First Name",
LastName = "Last Name"
}
}).Save();
var res = DB.Queryable<Book>()
.Select(b => new
{
Title = b.Title,
LastName = b.Author.LastName
}).ToArray();
foreach (var b in res)
{
Console.WriteLine($"title: {b.Title} / lastname: {b.LastName}");
}
Console.Read();
}
}
}
the above code is using my library MongoDB.Entities for brevity. simply replace DB.Queryable<Book>() with collection.AsQueryable() for the official driver.
I am doing a bot for VK on C# and faced to some problems. I have method which returns JSON like this
{
"ts": 1674111105,
"updates": [[4,
2262,
17,
61835649,
1534493714,
"",
{
"attach1_type": "doc",
"attach1": "61835649_472186415",
"title": " ... "
}
]]
}
This is object, as I see, but I cant get anything from the attach_type1 to title including. This is also an object, and it can't be transformed to string just like .ToString(), because in that case in the result I have System.Object. So, does anybody know how I can change this type or is it impossible?? I am in desperation.
I created a class for this object
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace CSharpVKbot.VK.UserLongPoll
{
[DataContract()]
public class Attachment
{
[DataMember(Name = "attach1_type")]
public string AttachType;
[DataMember(Name = "attach1")]
public string Attach;
[DataMember(Name = "title")]
public string Title;
}
}
created an object of this class
public Attachment DocId = new Attachment();
and then tried to change type to attachment, but it doesnt work either
case UpdateCode.NewMessage:
u.MessageID = (int)item[1];
u.Flags = (int)item[2];
u.PeerID = (int)item[3];
u.TimeStamp = (int)item[4];
u.Text = (string)item[5];
u.DocId = (Attachment)item[6];
break;
You need to deserialise the JSON - It cannot be just converted to an object.
Try something like
Attachment deserializedAttachement = new Attachment();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(item[6]));
DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedAttachment.GetType());
deserializedAttachment = ser.ReadObject(ms) as Attachment;
ms.Close();
Where item[6] is the string that represents the attachment information.
See - https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-serialize-and-deserialize-json-data#example
I think that you will have to iterate through all json properties.
This code may help you
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(YourJsonString);
foreach (var prop in obj)
{
if (prop is Newtonsoft.Json.Linq.JObject)
{
// Handle JObject
}
if (prop is Newtonsoft.Json.Linq.JProperty)
{
// Handle JProperty
}
}
There are many direction to resolve your problem.
I like it (using Newtonsoft):
JObject data = (JObject)JsonConvert.DeserializeObject(json);
var attach1_type = data.Descendants()
.OfType<JProperty>()
.FirstOrDefault(x => x.Name == "attach1_type")
?.Value;
numbers, strings, objects are in same array, which means they are boxed before returning to you. so your updates is List<List<object>> or object[][], whatever. your c# class, which match this json format, could be simply like this:
public class SomethingJsonResult
{
public int ts { get; set; }
public List<List<object>> updates { get; set; }
}
The 1st option is to use anonymous type:
public void ParseJsonResult(SomethingJsonResult result)
{
var definition = new
{
attach1_type = "",
attach1 = "",
title = ""
};
result?.updates?.ForEach(x =>
{
var update = JsonConvert.DeserializeAnonymousType(x[6], definition);
var attachment = new Attachment
{
AttachType = update.attach1_type,
Attach = update.attach1,
Title = update.title,
};
});
}
The 2nd option is a bit complex:
[DataContract()]
public class Attachment
{
[DataMember(Name = "attach1_type")]
[JsonProperty("attach1_type")] //Tell JsonConverter how to map your object
public string AttachType { get; set; }//Here is property, but not variable
[DataMember(Name = "attach1")]
[JsonProperty("attach1")]
public string Attach { get; set; }
[DataMember(Name = "title")]
[JsonProperty("title")]
public string Title { get; set; }
}
public void ParseJsonResult(SomethingJsonResult result)
{
result?.updates?.ForEach(update =>
{
//(Attachment)update[6] works only when your names of properties 100% match json objects
JsonConvert.DeserializeObject<Attachment>(update[6])
....
});
}
DataContractSerializer example:
https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.datamemberattribute?redirectedfrom=MSDN&view=netframework-4.7.2
you can implement everything inside your custom converter:
https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm
JsonConvert.DeserializeObject<AttachmentWrapper>(json, new AttachmentConverter(typeof(AttachmentWrapper)));
I am trying to create JSON like the following to pass to an external via TCP.
{"method": "dither", "params": [10, false, {"pixels": 1.5, "time": 8, "timeout": 40}], "id": 42}
I came close, but this is what I got instead:
{"method": "dither", "params": [10, false,"{"pixels": 1.5, "time": 8, "timeout": 40}"], "id": 42}
Notice the quote marks around the 3rd element of the params array.
I would appreciate any help in resolving this. Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Collections;
using System.Xml;
using System.Reflection;
namespace DitherTest
{
[CollectionDataContract]
public class DitherParametersList : ArrayList
{
public DitherParametersList() : base()
{}
}
[DataContract]
public class Dither
{
[DataMember( Name="method", Order=1)]
public string Method { get; set; }
[DataMember( Name="params", Order=2)]
public DitherParametersList Parameters { get; set; }
[DataMember( Name="id", Order=3)]
public int Id { get; set; }
}
[DataContract( Namespace="")]
public class Settle
{
[DataMember( Name = "pixels" )]
public double Pixels { get; set; }
[DataMember( Name = "time" )]
public int Time { get; set; }
[DataMember( Name = "timeout" )]
public int Timeout { get; set; }
public string SerializeJson()
{
return this.ToJSON();
}
}
static class Extensions
{
public static string ToJSON<T>( this T obj ) where T : class
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer( typeof( T ) );
using ( MemoryStream stream = new MemoryStream() )
{
serializer.WriteObject( stream, obj );
return Encoding.Default.GetString( stream.ToArray() );
}
}
}
class Program
{
static void Main( string[] args )
{
double ditherAmount = 10.0;
bool ditherRaOnly = false;
Settle settle = new Settle { Pixels = 1.5, Time = 8, Timeout = 40 };
DitherParametersList parameterList = new DitherParametersList();
parameterList.Add( ditherAmount );
parameterList.Add( ditherRaOnly );
string settleStr = settle.SerializeJson();
parameterList.Add( settleStr );
Dither dither = new Dither { Method = "dither", Parameters = parameterList, Id=42 };
string temp = dither.ToJSON();
}
}
}
Thanks in advance
you told it to make the third arg a string. You serialized it to a string then stuck it in as an arg.
you need
parameterList.Add( settle );
First of all, be sure to use newtonsoft.com/json like pm100 mentioned in his comment.
I've changed your code so that it would work with newtonsoft.json and got exactly what you've asked for:
{"method": "dither", "params": [10, false, {"pixels": 1.5, "time": 8, "timeout": 40}], "id": 42}
I removed the DitherParametersList you've created and used those models:
public class Dither
{
[JsonProperty("method", Order = 1)]
public string Method { get; set; }
[JsonProperty("params", Order = 2)]
public ArrayList Parameters { get; set; }
[JsonProperty("id", Order = 3)]
public int Id { get; set; }
}
public class Settle
{
[JsonProperty("pixels")]
public double Pixels { get; set; }
[JsonProperty("time")]
public int Time { get; set; }
[JsonProperty("timeout")]
public int Timeout { get; set; }
}
And serialized them easily:
class Program
{
static void Main(string[] args)
{
var settle = new Settle { Pixels = 1.5, Time = 8, Timeout = 40 };
var parameterList = new ArrayList { 10, false, settle };
var dither = new Dither { Method = "dither", Parameters = parameterList, Id = 42 };
string temp = JsonConvert.SerializeObject(dither);
}
}
The quotes are coming from the first serialization that you did here:
string settleStr = settle.SerializeJson();
Assuming that you want to avoid using the Newtonsoft library, an immediate fix would be to simply trim them off:
string settleStr = settle.SerializeJson().Trim('"');
A more robust solution would only require serialization one time. If you used a List{string} instead of a DitherParamtersList, you could do this:
Settle settle = new Settle { Pixels = 1.5, Time = 8, Timeout = 40 };
var parameterList = new List<string>()
{
ditherAmount.ToString(),
ditherRaOnly.ToString(),
string.Join(",", settle.Pixels, settle.Time, settle.Timeout)
};
Dither dither = new Dither { Method = "dither", Parameters = parameterList, Id = 42 };
string temp = dither.ToJSON();