Home > Net >  JSON parse to change String attribute to an object atribute in Java
JSON parse to change String attribute to an object atribute in Java

Time:07-01

I have a JSON object that one of the a attributes is a JSON string.

a = {
"dt" : "2022-01-02 00:00:00"
"fx": "{\"id\":1,\"faixaId\":1,\"speedAtivo\":true}",
"hash": "8c91a61a0a49b73de2fc13caed00e6a93dbe435b354216802da0dbe8bfda3300",
}

In JavaScript, I can convert the "fx" attribute to an object using:

a.fx = JSON.parse(a.fx)

And the new JSON:

a = {
"dt" : "2022-01-02 00:00:00"
"fx": {"id":1,
        "faixaId":1,
        "speedAtivo":true
      },
"hash": "8c91a61a0a49b73de2fc13caed00e6a93dbe435b354216802da0dbe8bfda3300",
}

There is a way to do this with Java?

CodePudding user response:

If you use Jackson lirary to convert objects from JSON String to objects via custom deserializer.

First you create Classes that will represent the main object and fx object

public class AClass {
    public String dt;
    @JsonDeserialize(using = Deserializer.class)
    public FxClass fx;
    public String hash;
}

public class FxClass {
    public int id;
    public int faixaId;
    public boolean speedAtivo;
}

Then you create deserizalizer

public class Deserializer extends StdDeserializer<FxClass> {
    protected Deserializer(Class<?> vc) {
        super(vc);
    }
    protected Deserializer() {
        this(null);
    }

    @Override
    public FxClass deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        TextNode treeNode = jsonParser.getCodec().readTree(jsonParser);
        return new ObjectMapper().readValue(treeNode.asText(), FxClass.class);
    }
}

And add deserializer to ObjectMapperConfiguration

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(FxClass.class, new Deserializer());
    mapper.registerModule(module);

And thats it. To convert JsonString to object

AClass readValue = new ObjectMapper.readValue(json, AClass.class);

For additional info try reading https://www.baeldung.com/jackson-deserialization

CodePudding user response:

yes, you can parse json string using one of these libraries to use these library check the docs and maven dependency

but make sure that your json is in correct format as the above json is missing comma after the first line ending

Below is the simple example to parse a json String using the above library.

String jsonStr = "{\"dt\":\"2022-01-02 00:00:00\",
    \"fx\":\"id\":1,\"faixaId\":1,\"speedAtivo\":true},
   \"hash\":\"8c91accsiamkFVXtw6N7DnE3QtredADYBYU35b354216802da0dbe8bfda3300\", 
}";

JSONObject strObj = JSONObject.fromObject(jsonStr);

Output: { "dt": "2022-01-02 00:00:00", "fx": { "id": 1, "faixaId": 1, "speedAtivo": true }, "hash": "8c91accsiamkFVXtw6N7DnE3QtredADYBYU35b354216802da0dbe8bfda3300" }

  • Related