Mam ten ciąg, który chcę iterować przez:
{"Imię": "John", "Nazwisko": "Doe"}
Chcę klucza i wartość, zarówno jak klucze mogą się zmienić i będą dynamiczne.
Próbowałem wiele sposobów, aby zachować i uzyskać wszystkie klucze i wartości, ale na próżno.
2 odpowiedzi
Możesz użyć biblioteki Jackson, aby konwertować ciąg do mapy:
final String jsonString = "{\"First Name\":\"John\",\"Last Name\":\"Doe\"}\"";
final Map<String, Object> jsonObject = new ObjectMapper().readValue(jsonString, Map.class);
Następnie możesz łatwo iterować na klucze i ich wartości.
Jedną z wielu opcji jest użycie Gson
za pomocą TypeAdapter
i pozwól, co zakładam, jest obiekt Person
do zakodowania i dekodowania za pomocą kluczy dynamicznych.
static class Person {
private final String firstName;
private final String lastName;
Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
static class PersonTypeAdapter extends TypeAdapter<Person> {
private final String firstNameKey;
private final String lastNameKey;
PersonTypeAdapter(String firstNameKey, String lastNameKey) {
this.firstNameKey = firstNameKey;
this.lastNameKey = lastNameKey;
}
@Override
public void write(JsonWriter out, Person value) throws IOException {
out.beginObject()
.name(firstNameKey).value(value.firstName)
.name(lastNameKey).value(value.lastName)
.endObject();
}
@Override
public Person read(JsonReader in) throws IOException {
in.beginObject();
String firstNameValue = null;
String lastNameValue = null;
while (in.hasNext()) {
String key = in.nextName();
if (key.equals(firstNameKey)) {
firstNameValue = in.nextString();
} else if (key.equals(lastNameKey)) {
lastNameValue = in.nextString();
} else {
throw new UnsupportedOperationException("Unsupported key.");
}
}
in.endObject();
if (firstNameValue == null || lastNameValue == null) {
throw new IllegalStateException("First name or last name is null.");
}
return new Person(firstNameValue, lastNameValue);
}
}
String json = "{\"First Name\":\"John\",\"Last Name\":\"Doe\"}\n" +
"\n";
Gson gson = new GsonBuilder()
.registerTypeAdapter(Person.class, new PersonTypeAdapter("First Name", "Last Name"))
.create();
Person person = gson.fromJson(json, Person.class);
Json result: com.Solution$Person@5f4da5c3[firstName=John,lastName=Doe]
Nowe pytania
java
Java to język programowania wysokiego poziomu. Użyj tego tagu, jeśli masz problemy z używaniem lub zrozumieniem samego języka. Ten tag jest rzadko używany samodzielnie i jest najczęściej używany w połączeniu z [spring], [spring-boot], [jakarta-ee], [android], [javafx], [hadoop], [gradle] i [maven].