您可以使用以下代码将给定的字符串转换为所需的格式:

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

public class Main {

    public static void main(String[] args) {
        String inputString = '[{"Name":"B1_SHB_4.DI1","Value":"False","Quality":true},{"Name":"B1_SHB_4.DI10","Value":"","Quality":false},{"Name":"B1_SHB_4.DI4","Value":"False","Quality":true},{"Name":"B1_SHB_4.DI5","Value":"False","Quality":true},{"Name":"B1_SHB_4.DI11","Value":"","Quality":false},{"Name":"B1_SHB_4.DI2","Value":"True","Quality":true}]';

        JSONArray jsonArray = new JSONArray(inputString);
        JSONObject outputJson = new JSONObject();

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String name = jsonObject.getString('Name').split('\.') [1];
            String value = jsonObject.getString('Value');
            Boolean quality = jsonObject.getBoolean('Quality');

            if (value.equals('True')) {
                outputJson.put(name, 1);
            } else if (value.equals('False')) {
                outputJson.put(name, 0);
            } else {
                outputJson.put(name, value);
            }
        }

        System.out.println(outputJson.toString());
    }
}

输出:

{"DI5":0,"DI4":0,"DI2":1,"DI10":"","DI1":0,"DI11":""}

请注意,此代码假定输入字符串的格式始终与所提供的示例字符串相同。如果该格式可能会有所不同,则需要进行适当的错误检查和处理。


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

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