Skip to content

Instantly share code, notes, and snippets.

@alexandreaquiles
Created June 21, 2022 22:01
Show Gist options
  • Save alexandreaquiles/cf337d3bcb59dd790ed2b08a0a4db7a3 to your computer and use it in GitHub Desktop.
Save alexandreaquiles/cf337d3bcb59dd790ed2b08a0a4db7a3 to your computer and use it in GitHub Desktop.
package br.com.alura.omnistream.service.json;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JsonParser {
private static final Pattern REGEX_ITEMS = Pattern.compile(".*\\[(.+)\\].*");
private static final Pattern REGEX_ATRIBUTOS_JSON = Pattern.compile("\"(.+?)\":\"(.*?)\"");
public List<Map<String, String>> parse(String json) {
Matcher matcher = REGEX_ITEMS.matcher(json);
if (!matcher.find()) {
throw new IllegalArgumentException("Não encontrou items.");
}
String[] items = matcher.group(1).split("\\},\\{");
List<Map<String, String>> dados = new ArrayList<>();
for (String item : items) {
Map<String, String> atributosItem = new HashMap<>();
Matcher matcherAtributosJson = REGEX_ATRIBUTOS_JSON.matcher(item);
while (matcherAtributosJson.find()) {
String atributo = matcherAtributosJson.group(1);
String valor = matcherAtributosJson.group(2);
atributosItem.put(atributo, valor);
}
dados.add(atributosItem);
}
return dados;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment