jodevelofer
jodevelofer

Reputation: 47

Create a class with JSON conditionally format

how can i convert this field in to Java Class field where myText field can be conditionally one of this format:

    {
       "myText" : "Values
    }


    {
       "myText" : ["text": "Values", "text2" : "Values"]
    }


public class MyClass {

   private String myText;

   //or 

   private MyText myText;

}

public class MyText {

    private String text1;
    private String text2;

}

Upvotes: 0

Views: 69

Answers (1)

Morph21
Morph21

Reputation: 1227

Welll.. you shouldn't do that in the first place.

But sometimes there is a case when some badly written rest api will return something like that. I have one solution which we are using only for parsing and sending through data.

So it works for us, but may not work for you

public class ListOrNotList {
  protected ListOrNotList() {

  }

  protected String get(Object item) {
    if (item instanceof String) {
        return (String)item;
    } else if (item instanceof List) {
        for (Object it : (List)item) {
            if (it instanceof LinkedHashMap) {
                LinkedHashMap hashMap = (LinkedHashMap) it;
                if (hashMap.containsKey("value")) {
                    Object value = hashMap.get("value");
                    if (value == null) {
                        return null;
                    }
                    return value.toString();
                }
            }
        }
    }
    return null;
  }
}

Then you make your class MyClass which extends from ListOrNotList

public class MyClass extends ListOrNotList {
  private Object myText;

  public String getMyText() {
    return get(myText); //This is method from ListOrNotList class
  }
}

This is not 100% working solution for OP, just an idea how it can be handled

In this example get function returns string or first element from List

you could also implement casting to T type in that method if you have a specific type and want to use any operations on it.

If you are creating api yourself then don't do things like returning different datatypes with the same name, it's bad practice and will harm development when anyone will try to integrate it in an app (including you after few months)

Upvotes: 2

Related Questions