serialize and deserialize json code example
Example 1: c# serialize json
using System.Text.Json;
var jsonString = JsonSerializer.Serialize(yourObject);
var obj = JsonSerializer.Deserialize<YourObject>(stringValue);
Example 2: object to json c#
using Newtonsoft.Json;
var jsonString = JsonConvert.SerializeObject(obj);
Example 3: java deserialize json
private Car parseCar(JsonNode node) {
Car car;
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule().addDeserializer(Car.class, new CarDeserializer());
mapper.registerModule(module);
organization = mapper.convertValue(node, Car.class);
return car;
}
public class CarDeserializer extends StdDeserializer<Car> {
public CarDeserializer() {
super(Car.class);
}
@Override
public Car deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JodaModule());
Car car = new Car();
car.setName(getValueAsText(root, "carName"));
car.setDoorCount(getValueAsInt(root,"doorCount"));
car.setColor(getValueAsText(root,"color"));
car.setType(getValueAsText(root,"type"));
return car;
}
}
Example 4: serialize and deserialize object in c#
Here's your model (with invented CT and TE) using protobuf-net (yet retaining the ability to use XmlSerializer, which can be useful - in particular for migration); I humbly submit (with lots of evidence if you need it) that this is the fastest (or certainly one of the fastest) general purpose serializer in .NET.
If you need strings, just base-64 encode the binary.
[XmlType]
public class CT {
[XmlElement(Order = 1)]
public int Foo { get; set; }
}
[XmlType]
public class TE {
[XmlElement(Order = 1)]
public int Bar { get; set; }
}
[XmlType]
public class TD {
[XmlElement(Order=1)]
public List<CT> CTs { get; set; }
[XmlElement(Order=2)]
public List<TE> TEs { get; set; }
[XmlElement(Order = 3)]
public string Code { get; set; }
[XmlElement(Order = 4)]
public string Message { get; set; }
[XmlElement(Order = 5)]
public DateTime StartDate { get; set; }
[XmlElement(Order = 6)]
public DateTime EndDate { get; set; }
public static byte[] Serialize(List<TD> tData) {
using (var ms = new MemoryStream()) {
ProtoBuf.Serializer.Serialize(ms, tData);
return ms.ToArray();
}
}
public static List<TD> Deserialize(byte[] tData) {
using (var ms = new MemoryStream(tData)) {
return ProtoBuf.Serializer.Deserialize<List<TD>>(ms);
}
}
}