Getting a string array from a JSON object within the deserialize method

I am working with a JSON object that looks like this:

{
  "name": "John",
  "age": 29,
  "bestFriends": [
    "Stan",
    "Nick",
    "Alex"
  ]
}

In my code, I have created a custom implementation of JsonDeserializer:

public class CustomDeserializer implements JsonDeserializer<Person>{
    @Override
    public Person deserialize(JsonElement json, Type type, JsonDeserializationContext cnxt){
        JsonObject object = json.getAsJsonObject();
        String name = new String(object.get("name").getAsString());
        Integer age = new Integer(object.get("age").getAsInt());
        // How to retrieve the string array for best friends here?
        return new Person(name, age, bestFriends);
    }
}

I'm using the GSON library. Can someone please provide guidance on how to extract a string array from the JSON object in this scenario?

Thank you in advance!

Answer №1

To work with the deserializer, simply iterate through the ArrayNode and append the values to your String[] sequentially.

ArrayNode contactsNode = (ArrayNode)object.get("contacts");
List<String> contactList = new ArrayList<String>();
for(JsonNode contact : contactsNode){
   contactList.add(contact.asText());
}
//if you need the String[]
contactList.toArray();

Answer №2

Give this a try, it should work perfectly. Thank you.

package example;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;


class Identity {

    private String uniqueId;

    public String getUniqueId() {
        return uniqueId;
    }

    public void setUniqueId(String uniqueId) {
        this.uniqueId = uniqueId;
    }

    @Override
    public String toString() {
        return "Identity [id=" + uniqueId + "]";
    }

}

public class Testing {

    public static void main(String[] args) {
        ObjectMapper mapper = new ObjectMapper();
        String jsonData = "{\"id\" : \"A001\"}";

        //convert to object
        try {
            Identity id = mapper.readValue(jsonData, Identity.class);
            System.out.println(id);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Answer №3

I would like to express my gratitude to everyone who took the time to respond to my inquiry, and at the same time, I have come to the conclusion (provided below) that best addresses my needs. The use of only GSON without any additional libraries seems to be the most suitable approach for me. At the time of posing my question, I was unaware that com.google.gson.TypeAdapter is a more efficient tool than JsonSerializer/JsonDeserializer. Below is the solution I have discovered for my particular issue:

package mytypeadapter;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

// Main class containing Person object
public class Main {
    static class Person{
       String name;
       int age;
       String[] bestFriends;

       // Default constructor
       Person() {}
       // Parameterized constructor
       Person(String name, int population, String... cities){
          this.name = name;
          this.age = population;
          this.bestFriends = cities;
       }
    }

    public static void main(String[] args) {
        // Nested PersonAdapter class extending TypeAdapter
        class PersonAdapter extends TypeAdapter<Person>{
            @Override
            public Person read (JsonReader jsonReader) throws IOException{
                Person country = new Person();
                List <String> cities = new ArrayList<>();
                jsonReader.beginObject();
                while(jsonReader.hasNext()){
                    switch(jsonReader.nextName()){
                        case "name":
                            country.name = jsonReader.nextString();
                            break;
                        case "age":
                            country.age = jsonReader.nextInt();
                            break;
                        case "bestFriends":
                            jsonReader.beginArray();
                            while(jsonReader.hasNext()){
                                cities.add(jsonReader.nextString());
                            }
                            jsonReader.endArray();
                            country.bestFriends = cities.toArray(new String[0]);
                            break;
                    }
                }
                jsonReader.endObject();
                return country;
            }

            @Override
            public void write (JsonWriter jsonWriter, Person country) throws IOException{
                jsonWriter.beginObject();
                jsonWriter.name("name").value(country.name);
                jsonWriter.name("age").value(country.age);
                jsonWriter.name("bestFriends");
                jsonWriter.beginArray();
                for(int i=0;i<country.bestFriends.length;i++){
                    jsonWriter.value(country.bestFriends[i]);
                }
                jsonWriter.endArray();
                jsonWriter.endObject();
            }
        }
        Gson gson = new GsonBuilder()
                    .registerTypeAdapter(Person.class, new PersonAdapter())
                    .setPrettyPrinting()
                    .create();
        Person person, personFromJson;
        person = new Person ("Vasya", 29, "Stan", "Nick", "Alex");
        String json = gson.toJson(person);
        personFromJson = new Person();
        personFromJson = gson.fromJson(json, personFromJson.getClass());
        System.out.println("Name = "+ personFromJson.name);
        System.out.println("Age = "+ personFromJson.age);
        for(String friend : personFromJson.bestFriends){
            System.out.println("Best friend "+ friend);
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Choose the DIV element based on its data attribute using JSON

When using each(), my goal is to: Hide all divs where the data-infos.grpid = $jQuery(this).data('infos').grpid Show the next div where data-infos.ordre = $jQuery(this).data('infos').next_ordre I am unsure how to apply a "where" ...

Guide on adding JSON data to a Common Data Service Entity using PowerApps

When it comes to inserting data entries into the Common Data Service (CDS) Entity in PowerApps, I encountered an issue. My entity has a specific structure which is easy to work with when importing data from an Excel table. However, when trying to import da ...

tally up the elements within the array

I want to tally the occurrences of likes and unlikes in an array. $content is structured as either {"userid":"1","like":"1"} or {"userid":"1","unlike":"1"}. The goal is to calculate the number of like and unlike records in a table. Currently, the displ ...

Sending requests through RoR and receiving JSON responses - what's next?

Hey there! So I'm diving into the world of Ruby on Rails and I've managed to create a form that sends data to an external widget which then returns JSON. Here's what my form looks like: <%= form_for :email, :url => 'http://XXX.X ...

Using jQuery's .each() method to iterate over a JSON object may only display the

Running into some trouble with jQuery.each(). I'm pulling JSON data from another PHP file and trying to display a specific key value from it. This is the JavaScript code I have: <div class="row" id="fetchmember"> <script type="text/javasc ...

Error: The object with the memory address 0x7f3f4bd01470 returned by the neo4j.work.result.Result is not compatible with JSON serialization

Hello, I am facing an error with the following code and need assistance in resolving it: class GenerateQuery: @staticmethod def get_nlg(graph_query): # graph = Graph("http://localhost:7474",auth=("neo4j", "pass" ...

php$json_data = json_decode($response);

I am brand new to PHP coming from a background in Python. I was fairly comfortable with retrieving JSON results from websites in Python, but for some reason, I can't seem to get it working in PHP. Here is the code snippet I'm using: <?php $ ...

Can anyone provide guidance on how to properly decode pusher.com's "serialized" JSON data into a QJsonDocument in Qt5?

Having trouble parsing JSON data received from a pusher.com WebSocket in my qt5 application. After identifying the issue, I'm unsure of how to resolve it: To illustrate, I created a small test program: QString str1 = "{\"event\":\"mes ...

Methods for extracting test data from Excel using Selenium

Currently, I am attempting to extract test data from an excel file for use in the sendkeys method. However, upon running my code, I encountered an error at this line: FileInputStream file = new FileInputStream (new File("C:\\Documents and Setting ...

Leverage decodable for personalized JSON parsing

I possess a json in this particular structure: { "route":{ "1":"Natural Attractiveness", "2":"Cultural Attractiveness", "3":"For Families with Children", "5":"For Seniors", "6":"For Eagles", "8":"Disabled" }, ...

I failed to utilize the search bar feature on Instagram

When I log in to Instagram, I try to search for "tanishq" in the search box but it doesn't work WebDriverWait wait = new WebDriverWait(driver, 10); WebElement search = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='e ...

What sets ExpectedConditions.refresh apart from ExpectedConditions.stalenessof in terms of functionality and usage?

I would greatly appreciate your assistance in clarifying the concepts of ExpectedConditions.refresh and ExpectedConditions.stalenessOf. ...

Efficiently fetching specific attributes from a Firebase object with precise content retrieval

Utilizing Firebase and Xamarin Forms, I am in the process of deploying an app. My goal is to find a way to retrieve an object (or multiple objects) that meet specific criteria. For instance, if I have a collection of characters with various attributes such ...

Steps for bypassing the authentication popup in Chrome browser during the execution of a Selenium script

click here for image descriptionWhen I try to log in with the first URL (as shown in the image), it takes me to another URL where I have to input my credentials. However, before reaching that page, a browser-generated pop-up appears that cannot be located ...

Converting UML diagrams into JSON Schema and XSD files

A simple UML diagram has been created as part of a larger cinema diagram. Link to Image Based on the diagram, Json Schema and XSD files were generated: Json Schema: -> movieSchema.json { "type": "object", "required": true, "properties" ...

Having trouble retrieving information from Node.js service in AngularJS 2

I am currently expanding my knowledge of Angular and attempting to retrieve data from a node js service using Angular 2 services. When I access the node js services directly from the browser, I can see the results. However, when I attempt to fetch the dat ...

Utilize accepts_nested_attributes_for to generate nested records during a put/post request

My project involves two primary models: Landscape Model: class Landscape < ActiveRecord::Base has_many :images, :as => :imageable accepts_nested_attributes_for :images, :allow_destroy => true attr_accessible :id, :name, :city, :state, :z ...

What is the best way to convert a graphql query into a JSON object?

I'm facing an issue where I need to convert a GraphQL query into a JSON object. Essentially, I have a query structured like the example below, and I'm seeking a method to obtain a JSON representation of this query. Despite my efforts in searching ...

Converting a Map to Json in Play Scala: A Step-by-Step Guide

Is there a way to convert the given Map structure, which is of type Map[String,Any], into JSON in Scala using Play framework? val result = s .groupBy(_.dashboardId) .map( each => Map( "dashboardId" -> each._1, "cubeId" -> ...

Unforeseen alterations in value occur in JavaScript when converting to JSON format

Having trouble generating a gantt chart from a JSON string, specifically with parsing the JSON string into a JSON object. I have a variable myString containing a JSON string that looks like this: {"c": [{"v": "496"}, {"v": "Task name 1"}, {"v": "9, "}, { ...