Manage one object inside list of object java.

huangapple go评论33阅读模式
英文:

Manage one object inside list of object java

问题

以下是已经翻译好的部分:

  1. Actual Response(实际响应):
[
    {
      "id": 21,
      "startDate": "2020-07-21",
      "startTime": "10:28:34+05:30",
      "endDate": "2020-07-21",
      "endTime": "19:28:34+05:30",
      "eventName": "Stretegic Planing for Business Success",
      "location": "America Phoenix",
      "city": "San Jose de Gracia",
      "eventImg": "Image Url",
      "passport": false,
      "passportDiscountPercent": 5,
      "featured": true,
      "myFavourite": true,
      "color": "Yellow"
    },
    {
      "id": 21,
      "startDate": "2020-07-21",
      "startTime": "10:28:34+05:30",
      "endDate": "2020-07-21",
      "endTime": "19:28:34+05:30",
      "eventName": "Stretegic Planing for Business Success",
      "location": "America Phoenix",
      "city": "San Jose de Gracia",
      "eventImg": "Image Url",
      "passport": false,
      "passportDiscountPercent": 5,
      "featured": true,
      "myFavourite": true,
      "color": "Green"
    },
    {
      "id": 76,
      "startDate": "2020-07-21",
      "startTime": "10:28:34+05:30",
      "endDate": "2020-07-21",
      "endTime": "19:28:34+05:30",
      "eventName": "Stretegic Planing for Business Success",
      "location": "string",
      "city": "Villa Juarez",
      "eventImg": "Imgage url",
      "passport": false,
      "passportDiscountPercent": 5,
      "featured": false,
      "myFavourite": true,
      "color": "Red"
    },
    {
      "id": 76,
      "startDate": "2020-07-21",
      "startTime": "10:28:34+05:30",
      "endDate": "2020-07-21",
      "endTime": "19:28:34+05:30",
      "eventName": "Stretegic Planing for Business Success",
      "location": "string",
      "city": "Villa Juarez",
      "eventImg": "Imgage url",
      "passport": false,
      "passportDiscountPercent": 5,
      "featured": false,
      "myFavourite": true,
      "color": "Black"
    }
]
  1. Expected Response(预期响应):
[
    {
      "id": 21,
      "startDate": "2020-07-21",
      "startTime": "10:28:34+05:30",
      "endDate": "2020-07-21",
      "endTime": "19:28:34+05:30",
      "eventName": "Stretegic Planing for Business Success",
      "location": "America Phoenix",
      "city": "San Jose de Gracia",
      "eventImg": "Image Url",
      "passport": false,
      "passportDiscountPercent": 5,
      "featured": true,
      "myFavourite": true,
      "eventType": [
            {
              "color": "Yellow"
            },
            {
              "color": "Green"
            }
      ]
    },
    {
      "id": 76,
      "startDate": "2020-07-21",
      "startTime": "10:28:34+05:30",
      "endDate": "2020-07-21",
      "endTime": "19:28:34+05:30",
      "eventName": "Stretegic Planing for Business Success",
      "location": "string",
      "city": "Villa Juarez",
      "eventImg": "Imgage url",
      "passport": false,
      "passportDiscountPercent": 5,
      "featured": false,
      "myFavourite": true,
      "eventType": [
            {
              "color": "Red"
            },
            {
              "color": "Black"
            }
      ]
    }
]
英文:

I have List of object that list of object is shown same object multiple time but only color field different for all duplicate object. I want to change response.

if anyone have solution for this create common method and pass this list and covert into as per my expectation response.

1.Actual Response

[
{
"id": 21,
"startDate": "2020-07-21",
"startTime": "10:28:34+05:30",
"endDate": "2020-07-21",
"endTime": "19:28:34+05:30",
"eventName": "Stretegic Planing for Business Success",
"location": "America Phoenix",
"city": "San Jose de Gracia",
"eventImg": "Image Url",
"passport": false,
"passportDiscountPercent": 5,
"featured": true,
"myFavourite": true,
"color": "Yellow"
},
{
"id": 21,
"startDate": "2020-07-21",
"startTime": "10:28:34+05:30",
"endDate": "2020-07-21",
"endTime": "19:28:34+05:30",
"eventName": "Stretegic Planing for Business Success",
"location": "America Phoenix",
"city": "San Jose de Gracia",
"eventImg": "Image Url",
"passport": false,
"passportDiscountPercent": 5,
"featured": true,
"myFavourite": true,
"color": "Green"
},
{
"id": 76,
"startDate": "2020-07-21",
"startTime": "10:28:34+05:30",
"endDate": "2020-07-21",
"endTime": "19:28:34+05:30",
"eventName": "Stretegic Planing for Business Success",
"location": "string",
"city": "Villa Juarez",
"eventImg": "Imgage url",
"passport": false,
"passportDiscountPercent": 5,
"featured": false,
"myFavourite": true,
"color": "Red"
},
{
"id": 76,
"startDate": "2020-07-21",
"startTime": "10:28:34+05:30",
"endDate": "2020-07-21",
"endTime": "19:28:34+05:30",
"eventName": "Stretegic Planing for Business Success",
"location": "string",
"city": "Villa Juarez",
"eventImg": "Imgage url",
"passport": false,
"passportDiscountPercent": 5,
"featured": false,
"myFavourite": true,
"color": "Black"
}
]    

2.Expect Response

[
{
"id": 21,
"startDate": "2020-07-21",
"startTime": "10:28:34+05:30",
"endDate": "2020-07-21",
"endTime": "19:28:34+05:30",
"eventName": "Stretegic Planing for Business Success",
"location": "America Phoenix",
"city": "San Jose de Gracia",
"eventImg": "Image Url",
"passport": false,
"passportDiscountPercent": 5,
"featured": true,
"myFavourite": true,
"eventType": [
{
"color": "Yellow"
},
{
"color": "Green"
}
]
},
{
"id": 76,
"startDate": "2020-07-21",
"startTime": "10:28:34+05:30",
"endDate": "2020-07-21",
"endTime": "19:28:34+05:30",
"eventName": "Stretegic Planing for Business Success",
"location": "string",
"city": "Villa Juarez",
"eventImg": "Imgage url",
"passport": false,
"passportDiscountPercent": 5,
"featured": false,
"myFavourite": true,
"eventType": [
{
"color": "Red"
},
{
"color": "Black"
}
]
}   
]    

答案1

得分: 2

Here's the translated code without the comments:

public class InitialModel {
    String id;
    String color;
}

public class Model {
    String id;
    List<Color> eventType = new ArrayList<>();

    class Color {
        String color;

        public Color(String color) {
            this.color = color;
        }
    }
}

List<Model> modelList = new ArrayList<>();
List<InitialModel> initialModelList = new Gson().fromJson(jsonString, new TypeToken<List<Model>>(){}.getType());

for (InitialModel initialModel : initialModelList) {
    Model tempModel = null;

    for(Model model : modelList){
        if(initialModel.id.equals(model.id)){
            tempModel = model;
            break;
        }
    }

    if(tempModel==null) {
        tempModel = new Model();
        tempModel.id = initialModel.id;
        modelList.add(tempModel);
    }
    tempModel.eventType.add(new Color(initialModel.color));
}

String resultJson = new Gson().toJson(modelList);

private List<EventCustomDTO> commonListView(List<EventDtoClass> eventDtoClassList) {
    List<EventCustomDTO> eventCustomDTOList = new ArrayList<>();
    List<EventDtoClass> eventDtoClasses = new Gson().fromJson(eventDtoClassList.toString(), new TypeToken<List<EventCustomDTO>>(){}.getType());
    
    for (EventDtoClass eventDtoClass : eventDtoClasses) {
        EventCustomDTO eventCustomDTO = null;
        
        for(EventCustomDTO model : eventCustomDTOList){
            if(eventDtoClass.getId().equals(model.getId())){
                eventCustomDTO = model;
                break;
            }
        }
        
        if(eventCustomDTO == null) {
            eventCustomDTO = new EventCustomDTO();
            eventCustomDTO.setId(eventDtoClass.getId());
            eventCustomDTOList.add(eventCustomDTO);
        }
        
        eventCustomDTO.getEventType().add(new TypesOfEvents(eventDtoClass.getEvenTypeId(), eventDtoClass.getColor()));
    }
    
    return eventCustomDTOList;
}

Please note that some parts of the code contain HTML-encoded characters (e.g., &lt; and &gt;). You may need to replace these with their actual characters for the code to work correctly.

英文:

Step 1: Create Schema Classes

Initial Response Model:

public class InitialModel {
String id;
String color;
}

Final/Converted Response Model:

public class Model {
String id;
List&lt;Color&gt; eventType = new ArrayList&lt;&gt;();
class Color {
String color;
public Color(String color) {
this.color = color;
}
}
}

Step 2: Iterate initial response and convert it to the final response

List&lt;Model&gt; modelList = new ArrayList&lt;&gt;();
List&lt;InitialModel&gt; initialModelList = new Gson().fromJson(jsonString, new TypeToken&lt;List&lt;Model&gt;&gt;(){}.getType());
for (InitialModel initialModel : initialModelList) {
Model tempModel = null;
// Check if model with same id already exists
for(Model model : modelList){
if(initialModel.id.equals(model.id)){
tempModel = model;
break;
}
}
// Create new model if id doesn&#39;t exists
if(tempModel==null) {
tempModel = new Model();
tempModel.id = initialModel.id;
modelList.add(tempModel);
}
tempModel.eventType.add(new Color(initialModel.color));
}

Result Json:

String resultJson = new Gson().toJson(modelList);

1.I have add your code but some error is getting

private List&lt;EventCustomDTO&gt; commonListView(List&lt;EventDtoClass&gt; eventDtoClassList) {
List&lt;EventCustomDTO&gt; eventCustomDTOList = new ArrayList&lt;&gt;();
List&lt;EventDtoClass&gt; eventDtoClasses = new Gson().fromJson(eventDtoClassList.toString(), new TypeToken&lt;List&lt;EventCustomDTO&gt;&gt;(){}.getType());
for (EventDtoClass eventDtoClass : eventDtoClasses) {
EventCustomDTO eventCustomDTO = null;
for(EventCustomDTO model : eventCustomDTOList){
if(eventDtoClass.getId().equals(model.getId())){
eventCustomDTO = model;
break;
}
}
if(eventCustomDTO == null) {
eventCustomDTO = new EventCustomDTO();
eventCustomDTO.getId() = eventDtoClass.getId();
eventCustomDTOList.add(eventCustomDTO);
}
eventCustomDTO.getEventType().add(new TypesOfEvents(eventDtoClass.getEvenTypeId(),eventDtoClass.getColor()));
}
return eventCustomDTOList;
}

答案2

得分: 1

以下是已翻译的部分:

由于您的预期结果中有不同的 JSON,您需要有两个类来进行序列化/反序列化。让我们考虑以下类:

@Getter
@AllArgsConstructor
private class ObjectA {
    public Long id;
    public String color;
}

@ToString
@AllArgsConstructor
private class ObjectB {
    public Long id;
    public String eventType;
}

现在,在这种情况下获得您期望的结果的代码可能如下所示:

List<ObjectA> object = List.of(new ObjectA(1L, "green"), new ObjectA(1L, "red"), new ObjectA(2L, "yellow"));
object.stream().collect(Collectors.groupingBy(ObjectA::getId))
        .entrySet() // from map of grouped ObjectA's
        .stream()
        .map(entry -> new ObjectB(entry.getKey(), // GroupID
                                  entry.getValue() // list of grouped ObjectA's by current GroupID
                                         .stream()
                                         .map(ObjectA::getColor) // change to stream of all color strings from grouped ObjectA's by current GroupID
                                         .collect(Collectors.joining(", ")))
        ).forEach(System.out::println);
        //.collect(Collectors.toList());

输出为:

ObjectB(id=1, eventType=green, red)
ObjectB(id=2, eventType=yellow)

您可以根据您的用例简单调整该代码。

英文:

Since you have different JSON in your expected result you will need to have 2 classes to serialize/deserialize from. Lets consider following classes:

@Getter
@AllArgsConstructor
private class ObjectA {
public Long id;
public String color;
}
@ToString
@AllArgsConstructor
private class ObjectB {
public Long id;
public String eventType;
}

Now the code to obtain your expected result in this case would be something like this:

List&lt;ObjectA&gt; object = List.of(new ObjectA(1L, &quot;green&quot;), new ObjectA(1L, &quot;red&quot;), new ObjectA(2L, &quot;yellow&quot;));
object.stream().collect(Collectors.groupingBy(ObjectA::getId))
.entrySet() // from map of grouped ObjectA&#39;s
.stream()
.map(entry -&gt; new ObjectB(entry.getKey(), // GroupID
entry.getValue() // list of grouped ObjectA&#39;s by current GroupID
.stream()
.map(ObjectA::getColor) // change to stream of all color strings from grouped ObjectA&#39;s by current GroupID
.collect(Collectors.joining(&quot;, &quot;)))
).forEach(System.out::println);
//.collect(Collectors.toList());

With output:

ObjectB(id=1, eventType=green, red)
ObjectB(id=2, eventType=yellow)

You can adjust that code simply for your use case.

huangapple
  • 本文由 发表于 2020年7月31日 16:22:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63188270.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定