-3

for example, I have this string

{"items":[{"match_id":"1-147440f1-7330-4c9c-9d3d-fab2e43e0754","version":2,"region":"EU"},{"match_id":"2-543985-ndakf-948129-dfsdafsda89fsda", "version":2","region":"EU"}

how can I get only the "1-147440f1-7330-4c9c-9d3d-fab2e43e0754", so the next characters after match_id that are between " ". I need them as string so not int or anything else, just string. Thank you!

Gl0deanR
  • 27
  • 8
  • 5
    Seems what you have here is not only a string but a JSON document. The best way to extract elements is to use a JSON parser. – Henry Jul 06 '20 at 06:17
  • Yes, sorry I forgot to mention that, I saved that to a String but yes it's JSON format. So I should try using some JSON module for Java or what? – Gl0deanR Jul 06 '20 at 06:23
  • 1
    Yes, there a plenty of them to choose from. – Henry Jul 06 '20 at 06:26

1 Answers1

2

This is using json-simple-1.1, you can download the jar or add the dependency via Maven/Gradle.

    String json = "{\"items\":[{\"match_id\":\"1-147440f1-7330-4c9c-9d3d-fab2e43e0754\",\"version\":2,\"region\":\"EU\"},{\"match_id\":\"2-543985-ndakf-948129-dfsdafsda89fsda\", \"version\":\"2\",\"region\":\"EU\"}]}";
    Object obj = new JSONParser().parse(json);

    JSONObject jo = (JSONObject) obj;
    
    JSONArray items = (JSONArray) jo.get("items");
    List<String> matchIds = new ArrayList<>();
    for(int i=0; i<items.size();i++) {
        JSONObject item = (JSONObject) items.get(i);    
        matchIds.add(item.get("match_id").toString());
    }
    
    System.out.println(matchIds.get(0));
Marc
  • 2,738
  • 1
  • 17
  • 21