我有一个带有内部嵌套对象的json字符串,如下所示:
{
"stringTypeCode": "aaaaa",
"choiceTypeCode1": {
"option1": true,
"option2": true
},
"choiceTypeCode2": {
"option3": true,
"option4": true
}
}
我需要将其转换为将嵌套对象保留为字符串的Map:
stringTypeCode - aaaaa
choiceTypeCode1 - {"option1": true,"option2": true}
choiceTypeCode2 - {"option2": true,"option3": true}
是否可以以简单的方式完成操作,最好没有任何库?
编辑:如果没有其他简单方法,则使用库。
Edit2:我在对象中具有可变数量的属性和变量名。
答案 0 :(得分:3)
将json解析为映射或通用json结构,遍历$inputFileType = 'Csv';
$inputFileNames = [
'./sampleData/example1.csv',
'./sampleData/example2.csv'
'./sampleData/example3.csv'
];
/** Create a new Reader of the type defined in $inputFileType **/
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
/** Extract the first named file from the array list **/
$inputFileName = array_shift($inputFileNames);
/** Load the initial file to the first worksheet in a `Spreadsheet` Object **/
$spreadsheet = $reader->load($inputFileName);
/** Set the worksheet title (to the filename that we've loaded) **/
$spreadsheet->getActiveSheet()
->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
/** Loop through all the remaining files in the list **/
foreach($inputFileNames as $sheet => $inputFileName) {
/** Increment the worksheet index pointer for the Reader **/
$reader->setSheetIndex($sheet+1);
/** Load the current file into a new worksheet in Spreadsheet **/
$reader->loadIntoExisting($inputFileName,$spreadsheet);
/** Set the worksheet title (to the filename that we've loaded) **/
$spreadsheet->getActiveSheet()
->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
}
对,然后根据key - value
对创建新映射。 key - toJsonString(value)
可能是简单的字符串,json对象,数字等...
通过一个简单的Jackson ObjectMapper:
value
您的示例产生:
String json = "YOUR JSON HERE";
ObjectMapper mapper = new ObjectMapper();
Iterator<Entry<String, JsonNode>> fields = mapper.readTree(json).fields();
Map<String, String> m = new HashMap<>();
while (fields.hasNext()) {
Entry<String, JsonNode> field = fields.next();
m.put(field.getKey(), mapper.writeValueAsString(field.getValue()));
}
m.entrySet().forEach(e -> System.out.println(e.getKey() + " - " + e.getValue()));