'Set value in static inner class and write object to JSON
What is a better way to set the value of the variable c in class Nested and then write the nested object to JSON instead of how it was done in the main method?
import lombok.Data;
@Data
public class Nested {
private A a;
@Data
public static class A {
private B b;
@Data
public static class B {
private int c;
}
}
}
import javax.json.bind.JsonbBuilder;
public class Main {
public static void main(String[] args) {
Nested nested = new Nested();
Nested.A a = new Nested.A();
Nested.A.B b = new Nested.A.B();
b.setC(123);
a.setB(b);
nested.setA(a);
System.out.println(JsonbBuilder.create().toJson(nested)); // Output: {"a":{"b":{"c":123}}}
}
}
Solution 1:[1]
You can just create both inner class A, B in Nested to reduce unnecessary hierarchy.
package com.example.demo;
package com.jason.empty;
import lombok.Data;
@Data
public class Nested {
private A a;
@Data
public static class A {
private B b;
}
@Data
public static class B {
private int c;
}
}
Note here import com.example.demo.Nested.A so that you can just use A a = new A(); instead of Nested.A a = new Nested.A(); to reduce the complexity.
Jackson is a good JSON serialization/deserialization library for Java. The ObjectMapper API provides a straightforward way to parse and generate JSON:
package com.example.demo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.example.demo.Nested.A;
import com.example.demo.Nested.B;
public class Main {
public static void main(String[] args) throws Exception {
B b = new B();
b.setC(123);
A a = new A();
a.setB(b);
Nested nested = new Nested();
nested.setA(a);
String json = new ObjectMapper().writeValueAsString(nested);
System.out.println(json); // Output: {"a":{"b":{"c":123}}}
}
}
Moreover
You could use @Accessors(chain = true) to chain multiple set operations together in one statement.
import lombok.Data;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
public class Nested {
private A a;
@Data
@Accessors(chain = true)
public static class A {
private B b;
}
@Data
@Accessors(chain = true)
public static class B {
private int c;
}
}
public static void main(String[] args) throws Exception {
B b = new B().setC(123);
A a = new A().setB(b);
Nested nested = new Nested().setA(a);
String json = new ObjectMapper().writeValueAsString(nested);
System.out.println(json); // Output: {"a":{"b":{"c":123}}}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
