gson Java:平面列表〈Map〈字符串,对象>>到层次结构列表〈Map〈字符串,对象>>

zvokhttg  于 2022-11-06  发布在  Java
关注(0)|答案(3)|浏览(205)

这个问题似乎很复杂,所以我在这里张贴这个问题的任何可能的方法来解决这个问题。
我有Map列表。我想再次Map列表,但要确保Map转换成某种层次结构。
原始数据:(列表〈Map〈字符串,对象〉〉)

[
  {
    "studentId": 101,
    "name": "John",
    "subjectId": 2001,
    "marks": 85,
    "street": "Bakers Street",
    "state": "LA"
  },
  {
    "studentId": 101,
    "name": "John",
    "subjectId": 2002,
    "marks": 75,
    "street": "Bakers Street",
    "state": "LA"
  },
  {
    "studentId": 102,
    "name": "Shae",
    "subjectId": 3001,
    "marks": 96,
    "street": "Howards",
    "state": "NYC"
  }
]

此Map列表将被转换为下面的Map列表:(列表〈Map〈字符串,对象〉〉)

[
  {
    "studentId": 101,
    "name": "John",
    "academics":
      [
        {
          "subjectId": 2001,
          "marks": 85
        },
        {
          "subjectId": 2002,
          "marks": 75
        }
      ],
    "address":
      {
        "street": "Bakers Street",
        "state": "LA"
      }
  },
  {
    "studentId": 102,
    "name": "Shae",
    "academics":
      [
        {
          "subjectId": 3001,
          "marks": 96
        }
      ],
    "address":
      {
        "street": "Howards",
        "state": "NYC"
      }
   }
]

作为一个天真的解决方案,我试图手动处理它们(真的很无聊),所以寻找任何有效和干净的方式来做它使用流或任何其他可能的方式。

UPDATE初始解决方案如下

public List<Map<String, Object>> transformResultSet(List<Map<String, Object>> flatDataList) {
    List<Map<String, Object>> hierarchicalDataList = new ArrayList<Map<String, Object>>();
    Map<String, List<Map<String, Object>>> studentIdToStudentDataListMap = new LinkedHashMap<>();

    for (Map<Integer, Object> flatData : flatDataList) {
        if (studentIdToStudentDataListMap.get(flatData.get("student_id")) == null) {
            studentIdToStudentDataListMap.put(Integer.valueOf(flatData.get("student_id").toString()), new ArrayList<Map<String, Object>>());
        }
        studentIdToStudentDataListMap.get(Integer.valueOf(flatData.get("student_id").toString())).add(flatData);
    }

    for (Map.Entry<Integer, List<Map<String, Object>>> studentFlatDataList : studentIdToStudentDataListMap.entrySet()) {
        Map<String, Object> studentHierarchicalDataMap = new LinkedHashMap<String, Object>();
        Map<String, Object> studentFlatDataMap = studentFlatDataList.getValue().get(0);
        studentHierarchicalDataMap.put("studentId", studentFlatDataMap.get("studentId"));
        studentHierarchicalDataMap.put("name", studentFlatDataMap.get("name"));

        List<Map<String, Object>> academicsList = new ArrayList<Map<String, Object>>();
        for (Map<String, Object> studentDetailAcademic : studentFlatDataList.getValue()) {
            Map<String, Object> academic = new LinkedHashMap<String, Object>();
            academic.put("subjectId", studentDetailAcademic.get("subjectId"));
            academic.put("marks", studentDetailAcademic.get("marks"));

            academicsList.add(academic);
        }
        studentHierarchicalDataMap.put("academics", academicsList);

        Map<String, Object> address = new LinkedHashMap<String, Object>();
        address.put("street", studentFlatDataMap.get("street"));
        address.put("state", studentFlatDataMap.get("state"));
        studentHierarchicalDataMap.put("address", address);

        hierarchicalDataList.add(studentHierarchicalDataMap);
    }
    return hierarchicalDataList;
}
mfuanj7w

mfuanj7w1#

从你的json样本看,你似乎有List<Object>而不是List<Map<String, Object>>。所以,***只是给予你一个想法***创建两个对象,让我们假设StudentDtoMarkDto
假设输入对象是Student和具有List<MarkDto>作为成员的StudentDto

Map<String, List<Student>>  map = list.stream().collect(groupingBy(Student::studentId)); 
Map<String, StudentDto>  dtoMap = new HashMap<>();
for(Map.Entry<String, List<Student>> entry : map.entrySet()) {
    StudentDto stud = new StudentDto();
    //assign other studentDto properties

    for(Student std : entry.getValue()) {
        MarkDto mark = new MarkDto();
        mark.setSubjectId(std.getStudentid());
        mark.setMark(entry.getMark()));

        stud.add(mark);
    }

    dtoMap.put(String.valueOf(stud.getId()), stud);
}

return dtoMap.stream().collect(Collectors.toList()); // or return the map itself
btxsgosb

btxsgosb2#

您可以将算法分成几个步骤:
1.将subjectIdmarks提取到一个新的academicsMap
1.将streetstate提取到一个新的addressMap
1.将academicsMap用一个List包裹。
1.按studentId合并数据,当发生冲突时,我们需要合并academicsList
步骤1.2.除了键名外都是一样的,我们可以把它提取到一个新的类中,避免重复的方法引用:

class ExtractKeysToMap implements Function<Map<String, Object>, Map<String, Object>> {

    private final List<String> keys;
    private final String newKey;

    ExtractKeysToMap(String newKey, List<String> keys) {
        this.newKey = Objects.requireNonNull(newKey);
        this.keys = Objects.requireNonNull(keys);
    }

    @Override
    public Map<String, Object> apply(Map<String, Object> map) {
        Map<String, Object> academics = new HashMap<>();
        keys.forEach(key -> {
            Object value = map.remove(key);
            if (value != null) academics.put(key, value);
        });
        map.put(newKey, academics);

        return map;
    }
}

由于我们已经实现了第一步和第二步,因此可以在以下示例中使用它:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.type.CollectionType;

import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./src/main/resources/test.json");

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        CollectionType jsonType = mapper.getTypeFactory().constructCollectionType(List.class, Map.class);
        List<Map<String, Object>> response = mapper.readValue(jsonFile, jsonType);

        final String academicsKey = "academics";
        Collection<Map<String, Object>> result = response
                .stream()
                .map(new ExtractKeysToMap(academicsKey, Arrays.asList("subjectId", "marks")))
                .map(new ExtractKeysToMap("address", Arrays.asList("street", "state")))
                .peek(map -> map.computeIfPresent(academicsKey, (k, v) -> new LinkedList<>(Collections.singletonList(v))))
                .collect(Collectors.toMap(
                        map -> map.get("studentId"),
                        map -> map,
                        (map0, map1) -> {
                            ((List<Object>) map0.get(academicsKey)).addAll((List<Object>) map1.get(academicsKey));

                            return map0;
                        }))
                .values();

        mapper.writeValue(System.out, result);
    }
}

以上代码打印:

[ {
  "studentId" : 101,
  "name" : "John",
  "academics" : [ {
    "subjectId" : 2001,
    "marks" : 85
  }, {
    "subjectId" : 2002,
    "marks" : 75
  } ],
  "address" : {
    "street" : "Bakers Street",
    "state" : "LA"
  }
}, {
  "studentId" : 102,
  "name" : "Shae",
  "academics" : [ {
    "subjectId" : 3001,
    "marks" : 96
  } ],
  "address" : {
    "street" : "Howards",
    "state" : "NYC"
  }
} ]
lf3rwulv

lf3rwulv3#

看起来您需要按学生分组,同时还要更改json结构。
在更高级别上,您可以执行以下操作(我们稍后将看到详细信息):

Map<Integer, Map<String, Object>> grouped = flatDataList.stream()
    .collect(Collectors.toMap(
        s -> (Integer) s.get("studentId"),
        s -> transformToHierarchicalStudent(s),
        (oldS, newS) -> mergeHierarchicalStudents(oldS, newS)));

因此,这将创建一个分层格式的学生Map,按studentId分组。我们将委托给两种方法:一个是从扁平学生创建分层学生,另一个是合并具有相同studentId的两个分层学生。
transformToHierarchicalStudent方法如下所示:

Map<String, Object> transformToHierarchicalStudent(Map<String, Object> flat) {

    Map<String, Object> student = new LinkedHashMap<>();

    student.put("studentId", flat.get("studentId"));
    student.put("name", flat.get("name"));

    Map<String, Object> address = new LinkedHashMap<>();
    address.put("street", flat.get("street"));
    address.put("state", flat.get("state"));
    student.put("address", address);

    List<Map<String, Object>> academics = new ArrayList<>();
    Map<String, Object> subject = new LinkedHashMap<>();
    subject.put("subjectId", flat.get("subjectId"));
    subject.put("marks", flat.get("marks"));
    academics.add(subject);
    student.put("academics", academics);

    return student;
}

mergeHierarchicalStudents方法:

Map<String, Object> mergeHierarchicalStudents(
        Map<String, Object> oldSt, Map<String, Object> newSt) {

    // We only need to merge the subjects
    List<Map<String, Object>> oldAcademics = 
        (List<Map<String, Object>>) oldSt.get("academics");
    List<Map<String, Object>> newAcademics = 
        (List<Map<String, Object>>) newSt.get("academics");
    oldAcademcis.addAll(newAcademics);

    return oldS;
}

这假定在原始平面列表中没有相同学生的重复科目。
最后,如果您需要一个List的分层学生,只需抓取map值即可:

List<Map<String, Object>> hierarchicalStudents = new ArrayList<>(grouped.values());

相关问题