CptSeasick
CptSeasick

Reputation: 28

Retrieve a list of strings from JSON in java

we are having trouble with getting a message out of a JSON message. We are rather confused by how the response is formatted since the key we receive for the list is empty but that isn't anything we can change. This is a response from a backend API that sends error messages when something goes wrong.

This is the JSON string. What we want to extract to a simple string is "Passwords must be at least 6 characters."

{
  "message": "The request is invalid.",
  "modelState": {
    "": [
      "Passwords must be at least 6 characters."
    ]
  }
}

What we have tried are a few things found over here and here but without any success.

Right now we are completely lost on how to get that one string out of that JSON message so literally any help is appreciated.

Regards, CptSeasick

Upvotes: 0

Views: 204

Answers (3)

Your modelState object's String is named as "". I mean empty string.

If you can change the name of it like below:

{
  "message": "The request is invalid.",
  "modelState": {
    "errorMessage": [
      "Passwords must be at least 6 characters."
    ]
  }
}  

and access your object like that:

myJSONobject.getJSONObject("modelState").getJSONArray("errorMessage").getString(0);

or just try :

myJSONobject.getJSONObject("modelState").getJSONArray("").getString(0);

Upvotes: 1

1218985
1218985

Reputation: 8022

You can do something like this:

package com.stackoverflow.answer;

import org.json.JSONObject;

public class JsonTest {

    public static void main(String[] args) {
        String response = "{ \"message\": \"The request is invalid.\", \"modelState\": { \"\": [ \"Passwords must be at least 6 characters.\"]}}";
        JSONObject jsonObject = new JSONObject(response);
        String errorMessage = jsonObject.getJSONObject("modelState").getJSONArray("").getString(0);
        System.out.println(errorMessage);
    }

}

Upvotes: 0

LeFex
LeFex

Reputation: 258

You can access it via

object.modelstate[""]

Upvotes: 1

Related Questions