Home > Net >  Splitting json object
Splitting json object

Time:09-11

I have JSON output from SQL statement as below

{
   "idno":6473853,
   "user":"GCA_GB",
   "operation":"U",
   "timestamp":"2022-08-22T13:14:48",
   "first_name":{
      "old":"rak",
      "new":"raki"
   },
   "fam_name":{
      "old":"gow",
      "new":"gowda"
   }
}

there is posibility that along with first name and family name we may get initial and nickname

i want to split above json as below

{
   "idno":6473853,
   "user":"GCA_GB",
   "operation":"U",
   "timestamp":"2022-08-22T13:14:48",
   "first_name":{
      "old":"rak",
      "new":"raki"
   }
}
{
   "idno":6473853,
   "user":"GCA_GB",
   "operation":"U",
   "timestamp":"2022-08-22T13:14:48",
   "fam_name":{
      "old":"gow",
      "new":"gowda"
   }
}

can someone help me with this

CodePudding user response:

Agree with Pshemo to create two separate JSON objects, here is an option:

const statement = {"idno":6473853,"user":"GCA_GB","operation":"U","timestamp":"2022-08-22T13:14:48","first_name":{"old":"rak","new":"raki"},"fam_name":{"old":"gow","new":"gowda"}}

const noFamName = {...statement};
delete noFamName['fam_name'];

const noFirstName = {...statement}:
delete noFirstName['first_name']

CodePudding user response:

package org.example;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import lombok.Getter;
import lombok.Setter;


public class GsonTest {
    @Getter
    @Setter
    public class oldNewClass{
        private String old;
        @SerializedName("new")
        private String _new;
    }
    @Getter @Setter
    public class SomeObject {
        private String idno;
        private String user;
        private String operation;
        private String timestamp;
        private oldNewClass first_name;
        private oldNewClass fam_name;
    }
    public static void main(String[] args) {
        Gson gson = new Gson();
        SomeObject s = gson.fromJson("{\"idno\":6473853,\"user\":\"GCA_GB\",\"operation\":\"U\",\"timestamp\":\"2022-08-22T13:14:48\",\"first_name\":{\"old\":\"rak\",\"new\":\"raki\"},\"fam_name\":{\"old\":\"gow\",\"new\":\"gowda\"}}", SomeObject.class);
        /* Access various properties */
        System.out.println(s.getFirst_name().get_new());
        /* Manipulate the object and then convert it back to json using */
        String jsonString = gson.toJson(s);
    }
}

Try the above code. Here are two of the maven dependencies for it.

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.9</version>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.24</version>
      <scope>provided</scope>
    </dependency>```
  • Related