简体   繁体   中英

Get string without square brackets

I have json like this

{"First":["Already exists"],"Second":["Already exists"]}

Currently I am doing like

JSONObject jObject = new JSONObject(myJson);
String first = jObject.getString("First")

But I am getting result like this

first = ["Already exists"]

But I want string without square brackets or ""

Try using JSONArray :

    JSONArray jArray = new JSONObject(myJson).getJSONArray("First");
    String first = jArray.getString(0);

Your json message with key 'first' is Array. So use should treat as Array.

String string = "{'First':['Already exists'],'Second':['Already exists']}";
    JSONObject jObject;
    try
    {
        jObject = new JSONObject(string);
        Object myJson = jObject.get("First");
        if(myJson instanceof JSONArray)
        {
            JSONArray jArray = jObject.getJSONArray("First");
            for (int i = 0; i < jArray.length(); i++)
            {
                System.out.println("val : "+jArray.getString(i));
            }
        }
    } catch (JSONException e)
    {
        e.printStackTrace();
    }

Thanks to @m.qadhavi i was able to figure out how it works

 //This was my temporary solution
 //get no. of garage
 properties.setPropertyFeaturesGarage(jsonObject
.getJSONObject("extras")
.getString("property_garages")
.replaceAll("[\"]", "")
.replace('[',' ')
.replace(']',' '));

But after going through @m.qadhavi explanation i corrected my code

 //get land size
 properties.setPropertyFeaturesLandSize(jsonObject
.getJSONObject("extras")
.getJSONArray("property_size")
.getString(0));

Happy Coding

Try to get Substring like eg

String first = jObject.getString("First")
String subFirst = first.substring(2,first.length()-2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM