0

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

1
  • It's good form to show what you've tried. For example, if the key weren't empty, would you know how to do it? What happens when you try this but with an empty string instead? Commented Oct 20, 2015 at 17:48

3 Answers 3

1

You can access it via

object.modelstate[""]
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

0

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);
    }

}

1 Comment

Thank you, this is exactly what we were searching for! We tried similar things before but this resolves our issue.

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.