Gson从Json转换为java类结构,其中属性名称未知 [英] Gson fromJson to java class structure where property names are not known
问题描述
{
details:{
interest: {
label:example1,
value:19,9,
symbol:%
},
monthly_invoice :{
label:example2,
value:29,
symbol:eur
},
start_fee :{
label:example3,
value:0,
symbol:eur
},
monthly_pay :{
label:example4,
value:58,
symbol:eur
}
}
$ b Details对象将包含具有相同属性的数量对象(标签,值,符号)。这是一种在java中创建类结构的方法,使用gson接收这些数据而不知道包含的对象的名称(interest,monthly_invoice ...)?
在您的Java代码中,details应该是一个
解决方案 pre> 映射< String,Foo>
其中Foo是具有标签,值和符号属性的类。例如你的JSON会解析成如下所示的类:
public class TestObject {
public Map< ; String,Foo>细节;
public static class Foo {
public String label;
public String value;
公共字符串符号;
$ / code>
然后在你的代码中你想要反序列化它一个Java实例,你会这样做:
Gson gson = new Gson();
TestObject testObject = gson.fromJson(json,TestObject.class);
System.out.println(testObject.details.get(interest)。label);
I have this json:
{
"details": {
"interest": {
"label": "example1",
"value": "19,9",
"symbol": "%"
},
"monthly_invoice": {
"label": "example2",
"value": "29",
"symbol": "eur"
},
"start_fee": {
"label": "example3",
"value": "0",
"symbol": "eur"
},
"monthly_pay": {
"label": "example4",
"value": "58",
"symbol": "eur"
}
}
}
The Details object will contain a dinamical number of objects with the same properties (label, value, symbol). It is a way to create a class structure in java, using gson to receive this data without known the name of the objects contained (interest, monthly_invoice...)?
Thanks!
In your Java code "details" should be a
Map<String, Foo>
Where Foo is your class with the label , value and symbol properties. e.g. you JSON would parse into a class that looks like this:
public class TestObject {
public Map<String, Foo> details;
public static class Foo {
public String label;
public String value;
public String symbol;
}
}
Then in your code where you want to deserialize it to a Java instance you would do this:
Gson gson = new Gson();
TestObject testObject = gson.fromJson(json, TestObject.class);
System.out.println(testObject.details.get("interest").label);
这篇关于Gson从Json转换为java类结构,其中属性名称未知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!