1

I have this code:

try {
    URL url = new URL("My api url");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.addRequestProperty("User-Agent", "MyUserAgent");

    InputStream inputStream = connection.getInputStream();
    InputStreamReader reader = new InputStreamReader(inputStream);

    JsonElement element = new JsonParser().parse(reader);

    System.out.println(element);
} catch (IOException e) {
    e.printStackTrace();
}

My api response:

[
  {
    "id": 12345,
    "name": "1.0"
  }
]

I need to get the name parameter as a string, but I don't know how to do it.

4
  • the name is a string no? "1.0" Commented Feb 14, 2020 at 15:25
  • @YCF_L yes, it is. Commented Feb 14, 2020 at 15:26
  • Ok, what did you mean by I need to get the name parameter as a string, but I don't know how to do it Commented Feb 14, 2020 at 15:26
  • I want to make a method that returns the name parameter. Commented Feb 14, 2020 at 15:27

1 Answer 1

1

I think you are looking for :

JsonElement name = element.getAsJsonArray().get(0).getAsJsonObject().get("name");

Output

"1.0"

Or to get the value of name :

String name = element.getAsJsonArray().get(0).getAsJsonObject().get("name").getAsString();

Output

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

8 Comments

If I need to compare the name value (version) to another, how I can do?
@alex3025 can you clarify your question more or by an example, I don't get you well
I want to exec code if the version that I get with name is greater than another string: "1.0.1"
@alex3025 this can be as another question, but I will give you a clue, you can add zeros to the end of the string which are low than your max version length, then remove the dots, and then convert the two strings to Integer and compare this two integers, for example in your case "1.0" -> "1.0.0" so you have "1.0.0" and "1.0.1" then -> "100" "101" then your action if (Integer.valueOf("100") > Integer.valueOf("101")), as I said, If you don't understand my solution, you can post a question and I will try to answer you step by step
I'm going to try what you write in the comment
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.