Punter Vicky
Punter Vicky

Reputation: 16992

Extract elements between first and last occurrence of characters

I have a json string which is part of another string -

This is a json {"name":"jim","age":12,"contactDetails": {"phone":"xxxxx"}} json ended

In this example , I would like to extract the string starting from first { and ending at last }.

Thanks for the answers. Below code works as suggested -

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String jsonData = "This is a json {\"name\":\"jim\",\"age\":12,\"contactDetails\": {\"phone\":\"xxxxx\"}} json ended";
        System.out.println(jsonData.substring(jsonData.indexOf("{"), jsonData.lastIndexOf("}") + 1));

    }


}

Upvotes: 0

Views: 82

Answers (2)

Chandan Suri
Chandan Suri

Reputation: 598

Your program above may not work when you have given a nested JSON, so for that purpose you should take the first index of { and the last index of }, so you should be using the functions such as Indexof and lastIndexof, because these will give you the required indexes and then you can easily get a substring out of it... Hopefully I solved your query, do ask if you need more clarification... Happy to help..

Upvotes: 1

Punter Vicky
Punter Vicky

Reputation: 16992

public class Test {    
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String jsonData = "This is a json {\"name\":\"jim\",\"age\":12,\"contactDetails\": {\"phone\":\"xxxxx\"}} json ended";
        System.out.println(jsonData.substring(jsonData.indexOf("{"), jsonData.lastIndexOf("}") + 1));

    }
}

Upvotes: 0

Related Questions