有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java提取第一个和最后一个字符之间的元素

我有一个json字符串,它是另一个字符串的一部分-

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

在本例中,我想提取从第一个{到最后一个}开始的字符串

谢谢你的回答。下面的代码按建议工作-

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

    }


}

共 (2) 个答案

  1. # 1 楼答案

    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));
    
        }
    }
    
  2. # 2 楼答案

    当你给出一个嵌套的JSON时,上面的程序可能无法运行,因此为此,你应该使用第一个{索引和最后一个}索引,所以你应该使用Indexof和lastIndexof等函数,因为这些函数将为你提供所需的索引,然后你可以很容易地从中得到一个子字符串。。。希望我解决了你的问题,问一下你是否需要更多的澄清。。。很乐意帮忙