gpt4 book ai didi

java - JSONArray 在编码时丢失

转载 作者:太空宇宙 更新时间:2023-11-04 13:57:03 28 4
gpt4 key购买 nike

好吧,这可能会令人困惑。

当某件事发生时,我试图将 jsonarray 添加到 jsonobject 中。目前,JSON 文件看起来有点像这样

{
"sweg":true,
"bans":[
{
"1":[
{
"reason":"Hacking"
}
]
}
],
"kicks":[
{
"1":[
{
"reason":"testing"
}
]
}
]
}

此外,如果文件格式错误,我们深表歉意。我必须手动设置空间。

下次运行,它应该看起来有点像

{
"sweg":true,
"bans":[
{
"1":[
{
"reason":"Hacking"
}
]
}
],
"kicks":[
{
"1":[
{
"reason":"testing"
}
],
"2":[
{
"reason":"meow"
}
]
}
]
}

当我说应该时,我的意思是意图是什么。添加的是“kicks”下的 JSONArray“2”。

但结果是这样的:

{
"sweg":true,
"bans":[
{
"1":[
{
"reason":"Hacking"
}
]
}
],
"kicks":[
{
"2":[
{
"reason":"meow"
}
]
}
]
}

最终丢失的是“kicks”下的“1”数组

编辑:忘记代码,这里是:

    public static void main(String[] args) {
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = new JSONObject();
try {
Object obj = jsonParser.parse(new FileReader("testing.json"));
jsonObject = (JSONObject) obj;
} catch (Exception ex) {
ex.printStackTrace();
}
JSONObject data = new JSONObject();
jsonObject.put("data", data);
JSONArray jsonArray11 = new JSONArray();
jsonObject.put("kicks", jsonArray11);
JSONObject placeHolder2 = new JSONObject();
jsonArray11.add(placeHolder2);
JSONArray kick2 = new JSONArray();
placeHolder2.p(2, kick2);
JSONObject jsonObject1 = new JSONObject();
kick2.add(jsonObject1);
jsonObject1.put("reason", "meow");
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File("testing.json"), false));
bufferedWriter.write(jsonObject.toJSONString());
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

最佳答案

我们没有足够的信息,但听起来您只想将数据附加kicks中。你可以这样做:

$json = '{
"sweg":true,
"bans":[
{
"1":[
{
"reason":"Hacking"
}
]
}
],
"kicks":[
{
"1":[
{
"reason":"testing"
}
]
}
]
}';
$jsonObj = json_decode($json);

$meow = '[
{
"reason":"meow"
}
]';
$meowObj = json_decode($meow);

/* This will count the fields in kicks[0], increment, and create a few field
and name the new field the resulting number, then insert the new object. */
$jsonObj->kicks[0]->{count((array)$jsonObj->kicks[0])+1} = $meowObj;

print_r($jsonObj);

这将导致:

stdClass Object
(
[sweg] => 1
[bans] => Array
(
[0] => stdClass Object
(
[1] => Array
(
[0] => stdClass Object
(
[reason] => Hacking
)

)

)

)

[kicks] => Array
(
[0] => stdClass Object
(
[1] => Array
(
[0] => stdClass Object
(
[reason] => testing
)

)

[2] => Array
(
[0] => stdClass Object
(
[reason] => meow
)
)
)
)
)

关于java - JSONArray 在编码时丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29712680/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com