0

I have a json string returning:

[{"TRAIN_JOURNEY_STAFF[],"ID":15,"EMAIL_ADDRESS":"jk@connectedrail.com","PASSWORD":"test","FIRST_NAME":"Joe","LAST_NAME":"Kevin","DATE_OF_BIRTH":"1996-04-20T00:00:00","GENDER":"Male","STAFF_ROLE":"Conductor","PHOTO":null},{new record..}]

There are several records here, I can't find a way to convert this json string to individual objects. I'm using the following to read in the data:

StringBuffer response;
    try (BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()))) {
        String inputLine;
        response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
    }
    System.out.print(response.toString());
}

I've tried the simple json libary but the parser mixes up the string, Which is not ideal as I need to output the data to rows object by object to jtables.

Any help would be appreciated.

Solved it with the below with GSON. Many thanks everyone!

    JsonElement jelement = new JsonParser().parse(response.toString());
    JsonArray jarray = jelement.getAsJsonArray();

    JsonObject jobject = jarray.get(0).getAsJsonObject();

    System.out.println(jobject.get("FIRST_NAME"));
Joe_K
  • 1
  • 2
  • 3
  • 3
    "TRAIN_JOURNEY_STAFF[] looks faulty.. should it be `"TRAIN_JOURNEY_STAFF":[]`? – Jack Flamp Apr 05 '19 at 10:13
  • A simple json string to json is transformed using `JSON.parse(myObj)`. No need for any extra libraries. However, as @JackFlamp mentioned, that json looks malformed – Raul Rene Apr 05 '19 at 10:14
  • Yeah that is strange, its the response I'm getting from the database from a GET – Joe_K Apr 05 '19 at 10:15
  • Possible duplicate of [Array of JSON Object to Java POJO](https://stackoverflow.com/questions/55248523/array-of-json-object-to-java-pojo) – Michał Ziober Apr 05 '19 at 10:17
  • 1
    To parse JSON in Java, read https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java. But what you have is not JSON, so that won't help. You should focus on determining why what you have is not JSON instead of trying to parse it. – JB Nizet Apr 05 '19 at 10:19
  • So `"TRAIN_JOURNEY_STAFF:[]` is a foreign key, being returned as an associative array. So I can't change it – Joe_K Apr 05 '19 at 10:34
  • your json looks invalid. I think it should be like that `[{"TRAIN_JOURNEY_STAFF":[],"ID":15,"EMAIL_ADDRESS":"jk@connectedrail.com","PASSWORD":"test","FIRST_NAME":"Joe","LAST_NAME":"Kevin","DATE_OF_BIRTH":"1996-04-20T00: 00: 00","GENDER":"Male","STAFF_ROLE":"Conductor","PHOTO":null},{}]` – Jitesh Prajapati Apr 05 '19 at 11:37

4 Answers4

1

You can use something like this:

public class ObjectSerializer {

private static ObjectMapper objectMapper;

@Autowired
public ObjectSerializer(ObjectMapper objectMapper) {
    ObjectSerializer.objectMapper = objectMapper;
}

public static <T> T getObject(Object obj, Class<T> class1) {
    String jsonObj = "";
    T userDto = null;
    try {
        jsonObj = objectMapper.writeValueAsString(obj);
        userDto = (T) objectMapper.readValue(jsonObj, class1);
        System.out.println(jsonObj);
    } catch (JsonProcessingException jpe) {
    } catch (IOException e) {
        e.printStackTrace();
    }
    return userDto;
}

Pass your JSON Object to this method alogn with class name and it will set the JSON data to that respective class.

Note: Class must have the same variables as in the JSON that you want to map with it.

Pawan Tiwari
  • 518
  • 6
  • 26
0

What you have basically is this :

[
  {
  "TRAIN_JOURNEY_STAFF":[
  ],
  "ID":15,
  "EMAIL_ADDRESS":"jk@connectedrail.com",
  "PASSWORD":"test",
  "FIRST_NAME":"Joe",
  "LAST_NAME":"Kevin",
  "DATE_OF_BIRTH":"1996-04-20T00:00:00",
  "GENDER":"Male",
  "STAFF_ROLE":"Conductor",
  "PHOTO":null
  },
  {

  }
]

You can use JSON constructor to serialize this array to an Array of JSONObjects. Try looking for JSONObject and JSONArray classes in Java. The constructor basically takes the stringified JSON (which you already have).

piet.t
  • 11,718
  • 21
  • 43
  • 52
Yash Soni
  • 456
  • 3
  • 11
0

Using org.json library:

JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");

see this

Niravdas
  • 371
  • 2
  • 19
0

You can use Jackson to convert JSON to an object.Include the dependency :

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.3</version>
</dependency>

Then make a POJO class to store the JSON .The pojo class should reflect the json string structure and should have appropriate fields to map the values(Here in sample code Staff.class is a pojo class).Then, by using ObjectMapper class you can convert the JSON string to a java object as follows :

StringBuffer response;
    try (BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()))) {
        String inputLine;
        response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
    }
    System.out.print(response.toString());

  ObjectMapper mapper = new ObjectMapper();

  //JSON from file to Object
  Staff obj = mapper.readValue(new File("c:\\file.json"), Staff.class);

  //JSON from String to Object 
  Staff obj = mapper.readValue(response.toString(), Staff.class);

Another simple method to read a JSON string and convert it into an object is :

JSON String:

{
     "lastName":"Smith",
    "address":{
        "streetAddress":"21 2nd Street",
         "city":"New York",
         "state":"NY",
         "postalCode":10021
    },
     "age":25,
     "phoneNumbers":[
            {
            "type":"home", "number":"212 555-1234"
            },
         {
            "type":"fax", "number":"212 555-1234"
         }
     ],
     "firstName":"John"
}

public class JSONReadExample  
{ 
    public static void main(String[] args) throws Exception  
    { 
        // parsing file "JSONExample.json" 
        Object obj = new JSONParser().parse(new FileReader("JSONExample.json")); 

        // typecasting obj to JSONObject 
        JSONObject jo = (JSONObject) obj; 

        // getting firstName and lastName 
        String firstName = (String) jo.get("firstName"); 
        String lastName = (String) jo.get("lastName"); 

        System.out.println(firstName); 
        System.out.println(lastName); 

        // getting age 
        long age = (long) jo.get("age"); 
        System.out.println(age); 

        // getting address 
        Map address = ((Map)jo.get("address")); 

        // iterating address Map 
        Iterator<Map.Entry> itr1 = address.entrySet().iterator(); 
        while (itr1.hasNext()) { 
            Map.Entry pair = itr1.next(); 
            System.out.println(pair.getKey() + " : " + pair.getValue()); 
        } 

        // getting phoneNumbers 
        JSONArray ja = (JSONArray) jo.get("phoneNumbers"); 

        // iterating phoneNumbers 
        Iterator itr2 = ja.iterator(); 

        while (itr2.hasNext())  
        { 
            itr1 = ((Map) itr2.next()).entrySet().iterator(); 
            while (itr1.hasNext()) { 
                Map.Entry pair = itr1.next(); 
                System.out.println(pair.getKey() + " : " + pair.getValue()); 
            } 
        } 
    } 
} 

For reference:
https://www.geeksforgeeks.org/parse-json-java/
https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/

Ananthapadmanabhan
  • 5,706
  • 6
  • 22
  • 39