通过 GSON 使用地图将 json 转换为 java pojo
我的 java pojo 看起来像这样
public class myPersonTO{
String name;
String surname;
Map<String, Double> categories;
}
,我正在使用 gson 库,但是我不确定我的 json 字符串以及它创建的对象应该是什么样的;我正在使用 json stringify,在包含两个字符串和一个对象数组的 javascript 对象上,请参阅伪代码:
var json = [];
jsonObject = new Object();
jsonObject.name = "testname"
jsonObject.surname = "testsurname"
var categories = [];
for(index=0,index <10;index++){
var category = new Object();
category.key = getKey();
category.value = index;
categories.push(category);
}
jsonObject.categories = categories;
json.push(jsonObject);
json = JSON.stringify(json); //convert json object, then use in submit
然后在 Java 中我使用以下内容:
Type listType = new TypeToken<List<myPersonTO>>() {}.getType();
List<myPersonTO> myPersonTOList = new Gson().fromJson(jsonString,listType);
非常感谢收到的任何帮助。干杯!
My java pojo looks like this
public class myPersonTO{
String name;
String surname;
Map<String, Double> categories;
}
I am using the gson library, however I an not sure what my json stringn, and the object it is created from should like; I am using json stringify, on a javascript object containing two strings and an array of objects, see pseudo code :
var json = [];
jsonObject = new Object();
jsonObject.name = "testname"
jsonObject.surname = "testsurname"
var categories = [];
for(index=0,index <10;index++){
var category = new Object();
category.key = getKey();
category.value = index;
categories.push(category);
}
jsonObject.categories = categories;
json.push(jsonObject);
json = JSON.stringify(json); //convert json object, then use in submit
and then in Java I am usign the following :
Type listType = new TypeToken<List<myPersonTO>>() {}.getType();
List<myPersonTO> myPersonTOList = new Gson().fromJson(jsonString,listType);
Any help gratefully received. Cheers !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题不是很清楚,但我认为其中一个对象的 JSON 版本如下所示:
编辑 - 好的,以响应您问题中的广泛更改:您的“类别”对象应该 <强>不是是一个数组。它应该是一个普通的对象,就像我的例子一样。好吧,至少我想象应该是这样。我必须检查这个“gson”的东西来确定,但是当我得知它希望 Java Map 实例被表示为数组时,我会感到有点惊讶(惊讶的是我发现了另一个库) 。
Your question isn't very clear, but I think the JSON verson of one of those objects would look like:
edit — OK in response to the extensive changes in your question: your "categories" object should not be an array. It should be a plain object, as in my example. Well, at least that's what I'd imagine it should be. I'd have to check this "gson" thing to make sure, but I'd be kind-of surprised to learn that it wants Java Map instances to be represented as arrays (surprised to the extent that I'd find another library).