如何在 Java 中使用 with 解析的索引

How to use index of with parsing in Java

我有一行具有特定格式的字符串给我带来了麻烦。我想取下面这行字符串:

String data = "[{\'ID\': 0001, \'Name\': Black Shirt, \'Cost\': 3.00, \'Asle\':1},{\'ID\': 0002, \'Name\': White Shirt, \'Cost\': 2.00, \'Asle\':1}]";

我要输出ID和Cost:

0001
3.00
0002
2.00

这是我的:

String data = "[{\'ID\': 0001, \'Name\': Black Shirt, \'Cost\': 3.00, \'Asle\':1},{\'ID\': 0002, \'Name\': White Shirt, \'Cost\': 2.00, \'Asle\':1}]";
String[] token = data.split("\'ID");
int firstindex = data.indexOf(",");
int lastindex = data.indexOf("");
String Id = null;
String Cost;
int i =1;
for(String s : token) {
    if (i==1) {
        Id = s.replaceFirst(data.substring(firstindex + 1, lastindex + 4), "");
        i++;
    } else {
        Cost = s.replaceFirst(data.substring(firstindex + 1, lastindex + 4), "");
    }
    System.out.print(Id);
    System.out.print(Cost);
}

我尝试 运行 时出现以下错误。

String index out of range: -9

我也遇到了一个错误,但无法为成本编制索引,我不确定为什么我不能像使用 Id 那样设置它。如果你能告诉我你是如何得到那个答案的,那就太好了。在我继续向其他人寻求帮助之前,我想确保我对字符串有一个坚定的理解。

试试下面的代码。我认为它可以准确地实现你想要做的事情。

public class Test {
    public static void main(String...strings) {
        String data = "[{\'ID\': 0001, \'Name\': Black Shirt, \'Cost\': 3.00, \'Asle\':1},{\'ID\': 0002, \'Name\': White Shirt, \'Cost\': 2.00, \'Asle\':1}]";

        int idFrom, idTo, costFrom, costTo;
        String idStr = "{\'ID\': ";
        String nameStr = ", \'Name\': ";
        String costStr = ", \'Cost\': ";
        String asleStr = ", \'Asle\'";
        while(data.indexOf(idStr) != -1) {
            idFrom = data.indexOf(idStr) + idStr.length();
            idTo = data.indexOf(nameStr);
            System.out.println(data.substring(idFrom, idTo));
            costFrom = data.indexOf(costStr) + costStr.length();
            costTo = data.indexOf(asleStr);
            System.out.println(data.substring(costFrom, costTo));
            data = data.substring(costTo + asleStr.length());
        }
    }
}

正如评论中提到的那样,JSON 像 Jackson or Gson 这样的解析器会让你的生活更轻松。

使用 Gson

JsonElement jelement = new JsonParser().parse(data);
JsonArray jarray = jelement.getAsJsonArray();
for(int i=0;jarray.size();i++){
    JsonObject  jobject = jarray.get(i).getAsJsonObject();
    String id = jobject.get("ID")..toString();
    String name = jobject.get("Name").toString();
    double cost = jobject.get("Cost").getAsDouble();
    String asle = jobject.get("Asle").toString();
}