Home > Blockchain >  Serializable field String JSON
Serializable field String JSON

Time:06-29

I have a class

public class ClassSerializable {

  private Long id;

  private String json;
}

Where field json = {"fieldJson": {"one": 1, "two": 1}}

If deserialize with ObjectMapper this object

String jsonString = mapper.writeValueAsString(objectСlassSerializable);

It turns out something like this:

{
  "id": 7,
  "json":"{\"fieldJson\": {\"one\": 1, \"two\": 1}}"
}

Escaping(\) has been added and there are quotation marks(") for the json field. How to get away from this correctly and make a single JSON? Something like this:

{
    "id": 7,
    "json": {
        "fieldJson": {
            "one": 1,
            "two": 1
        }
    }
}

CodePudding user response:

The behaviour is correct, but it is different from your intention.

You have an object with two fields:

  • id of type long
  • json of type String

but your intention is to store an object in the json field. You need to store it as an Object in java too. If you know that the json field will store only json objects you can define it as a Map<String, Object> that is the most generic type to store json objects. If it can be any kind of json valid entity you should use Object so it can store also json primitives (String, numbers) or arrays and not only objects.

So the best way to store it in java is

public class ClassSerializable {

  private Long id;

  // It can store any valid json object structure as java object
  // Change it to private Object json if it can store also primitives and arrays
  private Map<String, Object> json;
  
}

CodePudding user response:

The way that your program is set up right now, it serialises the json field as a string, and it does not know that it's supposed to be serialised as JSON. Therefore, you need to serialise the json field as an actual JSON object, store that in ClassSerializable, then serialise that instead.

Of course, you might need to include some other code to make it serialise properly, but the general idea is that you do need to specify it is an object and not just another string.

  • Related