0

I have a list of JSON like this store in the database:

  • Element 1:
{
  "detail": {
    "10": {
      "female": {
        "visited_person_count": 1,
        "visited_stay_time_sum": 10
      },
      "male": {
        "visited_person_count": 2,
        "visited_stay_time_sum": 20
      }
    },
    "20": {
      "female": {
        "visited_person_count": 3,
        "visited_stay_time_sum": 30
      },
      "male": {
        "visited_person_count": 4,
        "visited_stay_time_sum": 40
      }
    }
  }
}
  • Element 2:
{
  "detail": {
    "10": {
      "female": {
        "visited_person_count": 9,
        "visited_stay_time_sum": 90
      },
      "male": {
        "visited_person_count": 8,
        "visited_stay_time_sum": 80
      }
    },
    "20": {
      "female": {
        "visited_person_count": 7,
        "visited_stay_time_sum": 70
      },
      "male": {
        "visited_person_count": 6,
        "visited_stay_time_sum": 60
      }
    }
  }
}

... and so on

I want to combine all of these elements into one JSON contain sum of each element. The result like below

{
  "detail": {
    "10": {
      "female": {
        "visited_person_count": 10,
        "visited_stay_time_sum": 100
      },
      "male": {
        "visited_person_count": 10,
        "visited_stay_time_sum": 100
      }
    },
    "20": {
      "female": {
        "visited_person_count": 10,
        "visited_stay_time_sum": 100
      },
      "male": {
        "visited_person_count": 10,
        "visited_stay_time_sum": 100
      }
    }
  }
}

I used java to convert to HashMap and iterate the elements but it is very complicated. Is there a simpler way?

Please help me. Thank you in advance!

Jimmy
  • 1
  • 1

1 Answers1

0

First of all welcome to stackoverflow. Coming to your question, you can do this with JSONObject and a few controls (you can also handle these operations on the database side). I'm sharing a few questions from stackoverflow to guide you.

Merge (Concat) Multiple JSONObjects in Java

Java: Merging two json objects together with primary key

Don't forget to take a look at the previously asked questions, try to refactor for your issue and apply them. Good luck :)

Mustafa CEVIK
  • 23
  • 1
  • 10