/ / GSON: Jak przenosić pola do obiektu nadrzędnego - java, json, gson

GSON: Jak przenieść pola do obiektu nadrzędnego - java, json, gson

Używam Google GSON przekształcić mój obiekt Java w JSON.

Obecnie mam następującą strukturę:

"Step": {
"start_name": "Start",
"end_name": "End",
"data": {
"duration": {
"value": 292,
"text": "4 min."
},
"distance": {
"value": 1009.0,
"text": "1 km"
},
"location": {
"lat": 59.0000,
"lng": 9.0000,
"alt": 0.0
}
}
}

Obecnie a Duration obiekt znajduje się w środku Data obiekt. Chciałbym pominąć Data obiekt i przesuń Duration obiekt do Step obiekt, taki jak ten:

"Step": {
"start_name": "Start",
"end_name": "End",
"duration": {
"value": 292,
"text": "4 min."
},
"distance": {
"value": 1009.0,
"text": "1 km"
},
"location": {
"lat": 59.0000,
"lng": 9.0000,
"alt": 0.0
}
}

Jak mogę to zrobić za pomocą GSON?

EDYCJA: Próbowałem użyć TypeAdapter do modyfikacji klasy Step.class, ale w metodzie zapisu nie jestem w stanie dodać mojego obiektu Duration do JsonWriter.

Odpowiedzi:

3 dla odpowiedzi № 1

Prawdopodobnie możesz to zrobić, pisząc, a następnie rejestrując niestandardowy serializator dla Stepi upewniając się, że w nim pracujesz Duration itp. zamiast Data.

// registering your custom serializer:
GsonBuilder builder = new GsonBuilder ();
builder.registerTypeAdapter (Step.class, new StepSerializer ());
Gson gson = builder.create ();
// now use "gson" to do all the work

Poniższy kod niestandardowego serializatora piszę na czubku głowy. Pomija obsługę wyjątków i może się nie kompilować oraz spowalnia rzeczy, takie jak tworzenie instancji Gson wielokrotnie. Ale reprezentuje rodzaj rzeczy będziesz chciał zrobić:

class StepSerializer implements JsonSerializer<Step>
{
public JsonElement serialize (Step src,
Type typeOfSrc,
JsonSerializationContext context)
{
Gson gson = new Gson ();
/* Whenever Step is serialized,
serialize the contained Data correctly.  */
JsonObject step = new JsonObject ();
step.add ("start_name", gson.toJsonTree (src.start_name);
step.add ("end_name",   gson.toJsonTree (src.end_name);

/* Notice how I"m digging 2 levels deep into "data." but adding
JSON elements 1 level deep into "step" itself.  */
step.add ("duration",   gson.toJsonTree (src.data.duration);
step.add ("distance",   gson.toJsonTree (src.data.distance);
step.add ("location",   gson.toJsonTree (src.data.location);

return step;
}
}

0 dla odpowiedzi nr 2

Nie sądzę, że istnieje piękny sposób, aby to zrobić w gson. Może pobierz obiekt java (mapa) z początkowego json, usuń dane, umieść czas trwania i serializuj do json:

Map initial = gson.fromJson(initialJson);

// Replace data with duration in this map
Map converted = ...

String convertedJson = gson.toJson(converted);