How to Split a JSON string to two JSON objects in Java How to Split a JSON string to two JSON objects in Java json json

How to Split a JSON string to two JSON objects in Java


You can parse a json string with

var obj = JSON.parse(jsonString);

You can filter sub parts of a json object by simply addressing them

var token = obj.token;var user = obj.user;


The safer / cleaner way to do it is to create a POJO and deserialize your JSON into it using Jackson. Your pojo:

public class MyObject {    String token;    User user;    static class User {        int pk;        String username;        String email;        String first_name;        String last_name;    }}

Then, when you want to deserialize:

import com.fasterxml.jackson.databind.ObjectMapper;

and

ObjectMapper mapper = new ObjectMapper();MyObject myObject = mapper.readValue(jsonString, MyObject.class);String token = myObject.token;User user = myObject.user;...


You can split it this way:

// source objectJSONObject sourceObject = new JSONObject(sourceJson);String tokenKey = "token";// create new object for tokenJSONObject tokenObject = new JSONObject();// transplant token to new objecttokenObject.append(tokenKey, sourceObject.remove(tokenKey));// if append method does not exist use put// tokenObject.put(tokenKey, sourceObject.remove(tokenKey));System.out.println("Token object => " + tokenObject);System.out.println("User object => " + sourceObject);

Above code prints:

Token object => {"token":["eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9"]}User object => {"user":{"last_name":"","pk":17,"first_name":"","email":"user1@gmail.com","username":"user1"}}