convert form serialize to json object code example
Example 1: c# serialize json
using System.Text.Json;
var jsonString = JsonSerializer.Serialize(yourObject);
var obj = JsonSerializer.Deserialize<YourObject>(stringValue);
Example 2: java serialize object to json
public class someClass {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(MyAwesomeClass.class, new MyAwesomeSerializer());
mapper.registerModule(module);
jsonNode = mapper.convertValue(myAwesomeObject, JsonNode.class);
}
public class MyAwesomeSerializer extends StdSerializer<MyAwesomeClass> {
public MyAwesomeSerializer() {
super(MyAwesomeClass.class);
}
@Override
public void serialize(MyAwesomeClass myAwesomeClass, JsonGenerator jgen, SerializerProvider provider) throws IOException {
ObjectMapper mapper = new ObjectMapper();
jgen.writeStartObject();
jgen.writeStringField("name", myAwesomeClass.getName());
jgen.writeStringField("age", myAwesomeClass.getAge());
jgen.writeArrayFieldStart("hobbies");
for (Hobby hobby : myAwesomeClass.getHobbies()) {
jgen.writeObject(mapper.convertValue(hobby, JsonNode.class));
}
jgen.writeEndArray();
jgen.writeEndObject();
}
}