英文:
Design JSON in Java
问题
import java.util.Map;
public class MonthData {
private Map<String, DayData> data;
public Map<String, DayData> getData() {
return data;
}
public void setData(Map<String, DayData> data) {
this.data = data;
}
}
public class DayData {
private int A;
private int B;
public int getA() {
return A;
}
public void setA(int A) {
this.A = A;
}
public int getB() {
return B;
}
public void setB(int B) {
this.B = B;
}
}
In your Spring Boot application, you can use these classes to parse the JSON data. You can create a REST API endpoint that accepts the JSON input and uses Spring's @RequestBody
annotation to automatically convert the JSON into the MonthData
object. Here's a simplified example:
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ApiController {
@PostMapping("/parse-json")
public void parseJson(@RequestBody MonthData monthData) {
// Do something with the parsed data
}
}
Please make sure you have the necessary Spring Boot dependencies in your project for this to work.
英文:
I have an API which returns JSON in below format. Need to design Java class for the same. These values will be varying. So can't create a java class with fixed properties.
JSON as:
{
"jan": {
"2020-01-01": {
"A": 348,
"B": 408
},
"2020-01-02": {
"A": 348,
"B": 408
}
},
"feb": {
"2020-02-01": {
"A": 348,
"B": 408
},
"2020-02-02": {
"A": 348,
"B": 408
}
}
}
How to design Object in Spring Boot/Java for this?
答案1
得分: 2
我理解您正在寻找一个用于反序列化您分享的 JSON 结构的 Java 类。对我来说,这看起来像是:
Map<String, Map<String, Data>>
其中,
class Data {
private int A;
private int B;
}
现在,如果您想要使用例如 jackson 进行反序列化,您可以使用:
new ObjectMapper().readValue(myJson, new TypeReference<Map<String, Map<String, Data>>>() {});
英文:
I understand that you are looking for a java class to use to deserialize the JSON structure that you are sharing. This looks to me like
Map<String, Map<String, Data>>
Where
class Data {
private int A;
private int B;
}
Now if you want to deserialize it using for example jackson, you can use
new ObjectMapper().readValue(myJson, new TypeReference<Map<String, Map<String, Data>>>() {});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论