您可以使用Java中的JSONObject和JSONArray类来构建JSON数据。以下是使用这些类构建给定JSON字符串数据的示例代码:

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

public class Main {
    public static void main(String[] args) {
        JSONObject bill = new JSONObject();
        bill.put('year', '2022');
        bill.put('month', '01');
        bill.put('day', '02');
        bill.put('energyType', '电');
        bill.put('amount', '110.1');
        bill.put('cofficient', '0.12');

        JSONObject solarEnergy = new JSONObject();
        solarEnergy.put('year', '2022');
        solarEnergy.put('month', '01');
        solarEnergy.put('day', '02');
        solarEnergy.put('amount', '110.1');

        JSONObject json = new JSONObject();
        json.put('username', 'root');
        json.put('bill', bill);
        json.put('solarEnergy', solarEnergy);

        String jsonString = json.toString();
        System.out.println(jsonString);
    }
}

输出结果:

{"username":"root","bill":{"amount":"110.1","year":"2022","energyType":"电","day":"02","cofficient":"0.12","month":"01"},"solarEnergy":{"amount":"110.1","year":"2022","day":"02","month":"01"}}

在此示例中,我们首先创建了一个JSONObject实例bill,其中包含了账单相关的信息。然后,我们创建了一个JSONObject实例solarEnergy,其中包含了太阳能相关的信息。接着,我们创建了最外层的JSONObject实例json,并将上述两个JSONObject实例和其他键值对添加到json中。最后,我们使用toString()方法将json对象转换为字符串。

Java构建JSON字符串数据:使用JSONObject和JSONArray

原文地址: https://www.cveoy.top/t/topic/kLgG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录