0

Apologies, I have tried multiple things here and seem to run into some issues. This should be simple.

JSON file :

{
  "content": [
    {
      "media_type": "text/html",
      "text": "<p>Hello world</p>"
    },
    {
      "media_type": "text/plain",
      "text": "Hello world"
    }
  ],
  "id": "123",
  "title": "no-title"
}

I have a JSONObject created from this string.

I have tried -

String txtFromJSON = json.getJSONObject("content").getJSONObject("text").toString();


String txtFromJSON = json.getString("content.text");

String txtFromJSON = json.getString("content");

All of these fail.

The output I would like is simply the

<p>Hello world<p>

from the first text field.

Is there any simple way for me to get this data stored in a variable?

Thanks.

1
  • content is an array, not an object - it sounds like you should be using getJSONArray. A short but complete program demonstrating the problem would make it easier to help you though. Commented Jul 14, 2016 at 17:26

1 Answer 1

-2

try this:

final JSONObject obj = new JSONObject(youJsonString);
final JSONObject content = obj.getJSONArray("content");
final int n = content.length();
if(n ==1 ){

String txtFromJSON = json.getString("text");

}
Sign up to request clarification or add additional context in comments.

4 Comments

Why should they try that? What difference does it make? Why was their code wrong to begin with?
Agree with @SotiriosDelimanolis You provide absolutely no content to your answer as to why you think it is valid secondly your answer is completely wrong.
In this line String txtFromJSON = json.getString("content"); he try to get an Array, but he wants to receive only the string "Hello world" of the first text field (json.getString("text");).
Add that and all other details to your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.