gpt4 book ai didi

java - 无法正确创建 JSON

转载 作者:行者123 更新时间:2023-11-30 03:52:14 24 4
gpt4 key购买 nike

我正在尝试使用以下程序

  package com;


import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Test {
public static void main(String[] args) throws JSONException {



}

直到这里我都成功了

它正在产生 jsom 直到 leaf ,从那里我完全迷失了。

最佳答案

我不确定在您的实现中您是否尝试通过循环或递归来完成此操作,但是将值硬编码到 JSONObject 中,您可以通过以下方式完成您正在寻找的结构:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Test {
public static void main(String[] args) throws JSONException {
JSONObject leaf = new JSONObject().put("name", "500 ML");
JSONObject lemon = new JSONObject().put("name", "Lemon").put("leaf", new JSONArray().put(leaf));
JSONObject orange = new JSONObject().put("name", "Orange").put("leaf", new JSONArray().put(leaf));
JSONArray t3Array = new JSONArray().put(lemon).put(orange);
JSONObject bottled = new JSONObject().put("name", "Bottled").put("T3", t3Array);
JSONObject fountain = new JSONObject().put("name", "Fountain").put("T3", t3Array);
JSONObject softDrink = new JSONObject().put("T2", new JSONArray().put(bottled).put(fountain));
JSONObject json = new JSONObject().put("Soft Drinks", softDrink);

System.out.println(json);
}
}

关于java - 无法正确创建 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24149963/

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