简体   繁体   English

如何在java中使用非字符串键名创建JSON数组?

[英]How to create JSON array in java with non-string key names?

I am using this bootstrap transfer plugin at UI which i have to populate with the help of data sent from java application. 我在UI上使用这个bootstrap传输插件,我必须在java应用程序发送的数据的帮助下填充。 This plugin requires the data to be an array of objects with 'value' and 'content' properties. 此插件要求数据是具有“值”和“内容”属性的对象数组。 I can easily create a list in java and convert it to JSON array, but the problem here is that this plugin requires key names as non string names. 我可以轻松地在java中创建一个列表并将其转换为JSON数组,但问题是这个插件需要键名作为非字符串名称。 I tried using string key names but that just didn't worked. 我尝试使用字符串键名称但是没有用。 I looked up for ways to create non-string key names in JSON and the only way i could find was to write my own parser, and that was also not recommended. 我查找了在JSON中创建非字符串键名的方法,我找到的唯一方法是编写自己的解析器,这也是不推荐的。 So how can i prepare my data in java for this plugin ?? 那么如何在java中为这个插件准备我的数据呢?

Edit: As mentioned in the plugin documentation, here is a sample data to populate it. 编辑:如插件文档中所述,这里有一个填充它的示例数据。

$(function() {
...
var t = $('#test').bootstrapTransfer();
t.populate([
    {value:"1", content:"Apple"},
    {value:"2", content:"Orange"},
    {value:"3", content:"Banana"},
    {value:"4", content:"Peach"},
    {value:"5", content:"Grapes"}
]);
...

}); });

When i prepare a JSON array, it is like {"value":"1", "content":"Apple"} which doesn't work for this plugin. 当我准备一个JSON数组时,它就像{“value”:“1”,“content”:“Apple”}这对这个插件不起作用。

You might check how it runs again when you use a quoted string. 您可以在使用带引号的字符串时检查它是如何再次运行的。 When accessing a JSON object, the quotes for keys are not needed. 访问JSON对象时,不需要键的引号。 Take for example this code (in Nodejs): 以这个代码为例(在Nodejs中):

var console = require("console");
var data = { "value1" : 13,
    "value2" : "hello",
    value3: 15,
    value4 : "hello again" };

console.log("Value 1 = " + data.value1 );
console.log("Value 2 = " + data.value2 );
console.log("Value 3 = " + data.value3 );
console.log("Value 4 = " + data.value4 );

Some of the object is declared with quoted strings, and some are not. 一些对象用带引号的字符串声明,有些则不是。 All are accessed without the quotes, and my console shows: 所有都是在没有引号的情况下访问的,我的控制台显示:

Value 1 = 13
Value 2 = hello
Value 3 = 15
Value 4 = hello again

So it really shouldn't matter how your keys are defined in java. 因此,在Java中定义密钥的方式确实无关紧要。 I know that isn't an exact answer to your question of how to do it, but you really shouldn't need to. 我知道这不是你如何做到的问题的确切答案,但你真的不应该这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM