Tags down


How to handle NULL value in JSON Object using retrofit

By : Manoj
Date : October 14 2020, 08:10 PM
this will help Your call getProductColorMotor() can throw an exception. Do the following thing if you want safe Java code:
1) Mark the variable and getter as nullable
code :
private ProductColorResponse productColorMotor;

public ProductColorResponse getProductColorMotor() {
        return productColorMotor;
ProductColorResponse p = dataList.get(position)
if (p == null) { holder.txtColor.setText("Alt text") } else { holder.txtColor.setText(p.getColorName())

Share : facebook icon twitter icon

Retrofit - handle JSON key which has a dynamic structure - Array/Object

By : Karishma Gupta
Date : March 29 2020, 07:55 AM
This might help you I hope this will solve your problem.
First of all, in your case, if you have declared secondaryUser as object or Array, change it to List secondaryUser
code :
public class DynamicJsonConverter implements Converter {

    private static String fromStream(InputStream in) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder out = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {

        return out.toString();

    public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {
        try {
            InputStream in = typedInput.in(); // convert the typedInput to String
            String string = fromStream(in);
            in.close(); // we are responsible to close the InputStream after use
            return string;

        } catch (Exception e) { // a lot may happen here, whatever happens
            throw new ConversionException(e); // wrap it into ConversionException so retrofit can process it


    public TypedOutput toBody(Object object) { // not required
        return null;
 public class BasePathAdapterForDynamicJSONKeys {
        private static RetroFitInterface topRecommendationsInterface;

        public static RetroFitInterface getCommonPathInterface() {

            RestAdapter restAdapter = new RestAdapter.Builder()
                    .setConverter(new DynamicJsonConverter())

            topRecommendationsInterface = restAdapter.create(RetroFitInterface.class);
            return topRecommendationsInterface;
 public void success(String myData, Response response) {
 JSONObject mainObject = null;
 mainObject = new JSONObject(myData);

//You can also use JSONObject, depends on what type the response is

 JSONArray myJsonArray = mainObject.getJSONArray("yourkey");
 ArrayList<MyObj> menuDetails = new Gson().fromJson(myJsonArray.toString(), new TypeToken<List<MyObj>>(){}.getType());

Retrofit/GSON: how to handle response with both types: JSON object and JSON array?

By : Charles Wong
Date : March 29 2020, 07:55 AM
around this issue Use JsonParser to get JsonElement from string Determine type (e.g. JsonArray or JsonObject) of this JsonElement (via JsonElement::isJsonArray and JsonElement::isJsonObject) Parse result using Gson::fromJson
code :
static class Entity {
    String name;
    // other fields

static class Error {
    String errorName;
    // other fields

public static void main(String[] args) throws Exception {
    // no error
    String jsonString = "[{'name': 'one'}, {'name': 'two'}]";
    // error
    // String jsonString = "{'errorName': 'Not Found'}";

    Gson gson = new Gson();
    JsonElement jsonElement = new JsonParser().parse(jsonString);
    if (jsonElement.isJsonArray()) {
        // no error
        Entity[] entities = gson.fromJson(jsonElement, Entity[].class);
    } else if (jsonElement.isJsonObject()) {
        // error
        Error error = gson.fromJson(jsonElement, Error.class);
    } else {
        throw new IOException("Server response is not jsonElement array or jsonElement object");

Handle with null JSON object

By : Nuri Harman
Date : March 29 2020, 07:55 AM
should help you out I am new to JSON and jQuery. What I am doing is get the JSON object from the api and display it as a table. But some elements in JSON array are null , Can this meet your need?
code :
var noDataTip = 'No Information';
$.each(jsonarray, function(i,data) {
    $('<td>').text( (data.name && data.name.last) || noDataTip),
    $('<td>').text( (data.age && data.age.number)) || noDataTip).appendTo('.table');

How to handle JSON response of either a list of objects or a single object using retrofit?

By : Justin Goddard
Date : March 29 2020, 07:55 AM
will be helpful for those in need While the answer from @pirho seems to be applicable, I found out a different and simple solution which worked for me. Hopefully it may help others as well.
code :
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

    Retrofit retrofit = new Retrofit.Builder()

Retrofit response return null in onResponse function (single JSON object)

By : user3381868
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Seems like you're getting 422 as http status. Everything that is not a 2XX status code is treated as an error by retrofit and in such cases you access it using response.errorBody().
The not so great news is that it has to be manually converted. One way to do this is using response.errorBody().string().
Related Posts Related Posts :
  • Whitelabel Error Page instead of specific jsp page
  • Java. Remove a row from a matrix (array)
  • Trying to use listFiles() function, but array of files is empty, Java, Andriod Studio
  • Continue sleeping for remaining time when thread is interrupted
  • Android Studio SQLite database creation does not work?
  • Exporting a lazily initialized bean (which implements SelfNaming and is annotated with ManagedResource annotation) gives
  • Java Regex OR operator not working properly
  • "Invalid classification data: expect label value"
  • Intent .putExtra return null with PendingIntent
  • Draw shapes on scrollable JPanel
  • Can't connect to redis from spring inside docker container
  • Display base64-encoded image
  • Android cardview, change background color with switch listener
  • Multiple classpaths when running Ant taskdef?
  • Disabling sound on Android's Ongoing notification updating
  • ChartPanel not registering as a component in a GUI
  • Spring @Configuration not overriden in test context
  • How can i solve duplication of code in this?
  • Method undefined for object in java cannot be compiled and deployed
  • Peek at a value from an array with a probabilistic quantity
  • java - how to limit operation(e.g login) by cowndown timer
  • How can I search informations from file with names using input (java)?
  • 'Gradle cucumber' With testImplementation Not Working
  • Log4j2/Slf4j and Java 11
  • Subclasses with Java 8 lambdas and Optional
  • Optaplanner - Drools rules List<> memberOf List<>?
  • Problem with sending keys to a form field when there is no submit button available
  • Does anyone know how to add a value to org.w3c.dom.Element to instantiate both MiningSchema and SupportVectorMachineMode
  • Is it possible to use a different Spring Batch Sequence than the default one?
  • Java derby embedded DB error: The syntax of the string representation of a date/time value is incorrect
  • WeakReference of a Collection in java
  • Getting an average of doubles from ArrayList
  • Detecting circular references in Directed acyclic graph
  • Unexpected behavior sending object through socket in java
  • null object reference on data binding
  • Why am I getting an ArrayIndexOutOfBoundsException in this particular code?
  • Deserialize encrypted kafka message in consumer
  • Program using I/O & Strings. | Basic Inventory Markup Calculator
  • Kafka Avro Serializer and deserializer exception. Avro supported types
  • How to get links from HTML, correct usage of `doc.select`
  • Replace this lambda with a method reference
  • JsonPath ignore the Debug logs on output
  • Spring boot parsing @RequestBody
  • On KafkaProducer.send(message), I am getting "exception Error serializing Avro message"
  • How to perform throttling based on user defined argument?
  • ReadProcessMemory across module boundaries
  • How do I create varied colors for buttons in Java GUI?
  • Jackson LocalDate: one day off during serialization
  • Eclipse Milo: writing to an object member variable
  • JHipster/React - Get data from server anonymously (before login)
  • Oauth 2.0 - Single resource server but multiple client applications
  • How to transfer an int via DatagramSocket
  • How to make a layout for the equalizer?
  • JOOQ update set not populating values
  • Static variable being fed into JTextfield is only JTextfield that I am failing to update. Can't figure out why but I thi
  • Why exclude commons-logging when using slf4j?
  • How to fix error "contractor can't be apply upload to given types"?
  • Eclipse 2018-09 with jdk11 claims that package org.junit is missing even though it is included by maven
  • java linked list iterator error, output is displayed wrong
  • How to replace forward slash with triple forward slash in Java?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org