0

I'm having a problem where I'm receiving strings as a typical string or it comes in the form of a list.

For example, I could get:

"Hello world"

Or I could get:

["Hello", "world"]

What's the ideal way to detect the second type in a string object and concatenate accordingly?

Sorry, some code for context:

String result = "";

try
{
    result = json.getString("result"); //This could be one of the two options above
}
catch (JSONException e)
{
    // Do nothing
}
Geir Sagberg
  • 9,632
  • 8
  • 45
  • 60
ForeverLearning
  • 1,027
  • 1
  • 12
  • 30
  • What is the type of it? Do you need to parse the String? – Polygnome Oct 08 '16 at 09:34
  • Expand your question. No one reading this will have any idea what you are on about. – Alan Hay Oct 08 '16 at 09:35
  • Can you add some context to the question? Where are you using this? Is it a Java function? A RESTful API? What libraries can you use? – metacubed Oct 08 '16 at 09:35
  • Sorry, added some context. I am extracting a string from a JSON Object – ForeverLearning Oct 08 '16 at 09:38
  • 1
    So the context is JSON, being parsed in Java. `getString` will only ever get you the first option. You can check if `json.get("result") instanceof JsonArray` to see if it's an array. [ref](http://docs.oracle.com/javaee/7/api/javax/json/JsonArray.html) – BeyelerStudios Oct 08 '16 at 09:39
  • 1
    Ok.. now we need a bit more detail :) What is the type of the JSON object? Is it Jackson JSONObject? – metacubed Oct 08 '16 at 09:39
  • 1
    http://stackoverflow.com/questions/15920212/how-to-check-the-type-of-a-value-from-a-jsonobject – Ario Oct 08 '16 at 09:39
  • It's just standard JSON. Thanks for the comments, sorry for the confusion, thanks for the answer! – ForeverLearning Oct 08 '16 at 09:41
  • No problem please just search before ask questions :) – Ario Oct 08 '16 at 09:43
  • Will do! I guess in this case I wasn't sure how to approach asking the question either... Amateur hour. – ForeverLearning Oct 08 '16 at 09:44
  • If you are using Jackson to deserialize to a Java class that has some collection of Strings you can have Jackson handle a single String as an array: http://stackoverflow.com/questions/17003823/make-jackson-interpret-single-json-object-as-array-with-one-element – Alan Hay Oct 08 '16 at 09:55

0 Answers0