Ich habe Klassen wie diese:
class MyDate
{
int year, month, day;
}
class Lad
{
string firstName;
string lastName;
MyDate dateOfBirth;
}
Und ich möchte ein Lad
-Objekt in einen JSON-String wie folgt umwandeln:
{
"firstName":"Markoff",
"lastName":"Chaney",
"dateOfBirth":
{
"year":"1901",
"month":"4",
"day":"30"
}
}
(ohne Formatierung). Ich habe diesen Link gefunden, aber er verwendet einen Namespace, der nicht in .NET 4 ist. Ich habe auch von JSON.NET gehört, aber die Site scheint momentan nicht erreichbar zu sein, und ich bin nicht begeistert über die Verwendung externer DLL -Dateien. Gibt es neben dem manuellen Erstellen eines JSON-Zeichenfolgenschreibers weitere Optionen?
Sie können die Klasse JavaScriptSerializer
verwenden (Verweis auf System.Web.Extensions
hinzufügen):
using System.Web.Script.Serialization;
var json = new JavaScriptSerializer().Serialize(obj);
Ein vollständiges Beispiel:
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);
}
}
Da wir alle einen Liner lieben
... dies hängt vom Newtonsoft NuGet-Paket ab, das populärer und besser als der Standard-Serializer ist.
Newtonsoft.Json.JsonConvert.SerializeObject(new {foo = "bar"})
Dokumentation: Serialisierung und Deserialisierung von JSON
Verwenden Sie Json.Net library. Sie können es von Nuget Packet Manager herunterladen.
Serialisierung zu 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);
Deserialisierung zum Objekt:
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Lad>(jsonString );
Wooou! Wirklich besser mit einem JSON-Framework :)
Hier ist mein Beispiel mit 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
}
}
}
Der 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();
}
}
}
Das Ergebnis:
{
"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
}
]
}
Jetzt werde ich die Konstruktormethode implementieren, die eine JSON-Zeichenfolge empfängt und die Felder der Klasse auffüllt.
Wenn Sie sich in einem ASP.NET MVC-Webcontroller befinden, ist das so einfach wie folgt:
string ladAsJson = Json(Lad);
Kann nicht glauben, dass niemand dies erwähnt hat.
Wenn sie nicht sehr groß sind, exportieren Sie den Fall wahrscheinlich als Json . Dies macht auch alle Plattformen plattformfähig
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);
}
Sie können dies erreichen, indem Sie Newtonsoft.json verwenden. Installieren Sie Newtonsoft.json von Nuget. und dann:
using Newtonsoft.Json;
var jsonString = JsonConvert.SerializeObject(obj);
Verwenden Sie this tools , um eine C # -Klasse zu generieren, und verwenden Sie diesen Code, um Ihr Objekt zu serialisieren
var json = new JavaScriptSerializer().Serialize(obj);
Verwenden Sie den folgenden Code, um XML in JSON zu konvertieren.
var json = new JavaScriptSerializer().Serialize(obj);
So einfach funktioniert das auch für dynamische Objekte (Typobjekt):
string json = new
System.Web.Script.Serialization.JavaScriptSerializer().Serialize(MYOBJECT);
Ich würde für den JSON-Serializer von ServiceStack stimmen:
using ServiceStack.Text
string jsonString = new { FirstName = "James" }.ToJson();
Es ist auch das schnellste JSON-Serialisierungsprogramm für .NET: http://www.servicestack.net/benchmarks/
Es gibt dieses wirklich nette Dienstprogramm hier: http://csharp2json.io/
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);
}
}
Objekt
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;
}
}
Implementierung
var jsonObject = new AppConfigurationSettings();
WriteToJsonFile<AppConfigurationSettings>(file.FullName, jsonObject);
Ausgabe
{
"AppSettings": {
"DebugMode": false
}
}