JSON parsing using Gson for Java
Chciałbym przeanalizować dane z JSON, który jest typu String
.
Używam Google Gson .
Mam:
jsonLine = "
{
"data": {
"translations": [
{
"translatedText": "Hello world"
}
]
}
}
";
A moja klasa to:
public class JsonParsing{
public void parse(String jsonLine) {
// there I would like to get String "Hello world"
}
}
11 answers
Jest to prosty kod, aby to zrobić, unikałem wszystkich kontroli, ale to jest główna idea.
public String parse(String jsonLine) {
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("data");
JsonArray jarray = jobject.getAsJsonArray("translations");
jobject = jarray.get(0).getAsJsonObject();
String result = jobject.get("translatedText").getAsString();
return result;
}
Aby uczynić użycie bardziej ogólnym-przekonasz się, że javadocs Gsona są dość jasne i pomocne.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-19 15:45:31
W mojej pierwszej aplikacji gson unikałem używania dodatkowych klas do przechwytywania wartości głównie dlatego, że używam json do spraw config
Pomimo braku informacji (nawet strony gson), to znalazłem i wykorzystałem:
Począwszy od
Map jsonJavaRootObject = new Gson().fromJson("{/*whatever your mega complex object*/}", Map.class)
Jest to jedna z najbardziej rozpoznawalnych map na świecie.]}
Za każdym razem, gdy gson widzi", tworzy łańcuch
Za każdym razem, gdy gson widzi liczbę, tworzy podwójną
Za każdym razem, gdy gson widzi [], to tworzy ArrayList
Możesz wykorzystać te fakty (połączone) na swoją korzyść
Wreszcie jest to kod, który sprawia, że rzecz
Map<String, Object> javaRootMapObject = new Gson().fromJson(jsonLine, Map.class);
System.out.println(
(
(Map)
(
(List)
(
(Map)
(
javaRootMapObject.get("data")
)
).get("translations")
).get(0)
).get("translatedText")
);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-07 00:32:02
Najprostszą rzeczą jest zwykle stworzenie pasującej hierarchii obiektów, tak:
public class Wrapper {
public Data data;
}
static class Data {
public Translation[] translations;
}
static class Translation {
public String translatedText;
}
A następnie bind za pomocą GSON, przemierzaj hierarchię obiektów przez pola. Dodawanie getterów i setterów jest bezcelowe dla podstawowych kontenerów danych.
Więc coś w stylu:
Wrapper value = GSON.fromJSON(jsonString, Wrapper.class);
String text = value.data.translations[0].translatedText;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-31 21:14:42
Możesz utworzyć odpowiednie klasy Javy dla obiektów json. Liczba całkowita, wartości łańcuchowe mogą być odwzorowywane tak, jak jest. Json może być parsowany w ten sposób -
Gson gson = new GsonBuilder().create();
Response r = gson.fromJson(jsonString, Response.class);
Oto przykład - http://rowsandcolumns.blogspot.com/2013/02/url-encode-http-get-solr-request-and.html
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-11 18:57:44
Możesz użyć oddzielnej klasy do reprezentowania obiektu JSON i użyć adnotacji @SerializedName
do określenia nazwy pola do pobrania dla każdego elementu danych:
public class Response {
@SerializedName("data")
private Data data;
private static class Data {
@SerializedName("translations")
public Translation[] translations;
}
private static class Translation {
@SerializedName("translatedText")
public String translatedText;
}
public String getTranslatedText() {
return data.translations[0].translatedText;
}
}
Następnie możesz wykonać parsowanie w swojej metodzie parse() używając obiektu Gson
:
Gson gson = new Gson();
Response response = gson.fromJson(jsonLine, Response.class);
System.out.println("Translated text: " + response.getTranslatedText());
Dzięki temu podejściu, możesz ponownie użyć klasy Response
, Aby dodać inne dodatkowe pola, aby odebrać inne elementy danych, które chcesz wyodrębnić z JSON-w przypadku, gdy chcesz wprowadzić zmiany, aby uzyskać wyniki dla, powiedzmy, wielu tłumaczeń w jednym wywołania, lub aby uzyskać dodatkowy ciąg znaków dla wykrytego języka źródłowego.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-26 02:59:32
Używanie Gson do rozwiązywania
Chciałbym utworzyć klasę dla poszczególnych parametrów w łańcuchu JSON. Alternatywnie możesz utworzyć jedną klasę główną o nazwie "Data", a następnie utworzyć klasy wewnętrzne w podobny sposób. Stworzyłem osobne klasy dla jasności.
Klasy są następujące.
- Dane
- tłumaczenia
- TranslatedText
W klasie JsonParsing wywołujemy metodę "parse" gson.fromJson(jsonLine, Data.class)
, która skonwertuje Łańcuch znaków w obiektach Javy za pomocą Odbicie.
Po uzyskaniu dostępu do obiektu "Data" możemy uzyskać dostęp do każdego parametru indywidualnie.
Nie miałem okazji przetestować tego kodu, ponieważ jestem z dala od mojej maszyny deweloperskiej. Ale to powinno pomóc.
Kilka dobrych przykładów i articles.
http://albertattard.blogspot.com/2009/06/practical-example-of-gson.html
http://sites.google.com/site/gson/gson-user-guide
Kod
public class JsonParsing{
public void parse(String jsonLine) {
Gson gson = new GsonBuilder().create();
Data data = gson.fromJson(jsonLine, Data.class);
Translations translations = data.getTranslation();
TranslatedText[] arrayTranslatedText = translations.getArrayTranslatedText(); //this returns an array, based on json string
for(TranslatedText translatedText:arrayTranslatedText )
{
System.out.println(translatedText.getArrayTranslatedText());
}
}
}
public class Data{
private Translations translations;
public Translations getTranslation()
{
return translations;
}
public void setTranslation(Translations translations)
{
this.translations = translations;
}
}
public class Translations
{
private TranslatedText[] translatedText;
public TranslatedText[] getArrayTranslatedText()
{
return translatedText;
}
public void setTranslatedText(TranslatedText[] translatedText)
{
this.translatedText= translatedText;
}
}
public class TranslatedText
{
private String translatedText;
public String getTranslatedText()
{
return translatedText;
}
public void setTranslatedText(String translatedText)
{
this.translatedText = translatedText;
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-30 20:17:16
JsonParser parser = new JsonParser();
JsonObject jo = (JsonObject) parser.parse(data);
JsonElement je = jo.get("some_array");
//Parsing back the string as Array
JsonArray ja = (JsonArray) parser.parse(o.get("some_array").getAsString());
for (JsonElement jo : ja) {
JsonObject j = (JsonObject) jo;
// Your Code, Access json elements as j.get("some_element")
}
Prosty przykład do analizy JSON w taki sposób
{ "some_array": "[\"some_element\": 1,\ " some_more_element\": 2]" , "some_other_element": 3 }
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-16 09:32:30
Najpierw Wygeneruj Getter i Setter używając poniższej strony parsowania
Http://www.jsonschema2pojo.org/
Teraz użyj Gson
GettetSetterClass object=new Gson().fromjson(jsonLine,GettetSetterClass.class);
Teraz użyj obiektu, aby uzyskać wartości takie jak data, translationText
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-24 06:58:12
Możesz użyć zapytania JsonPath, aby wyodrębnić wartość. A z JsonSurfer , który jest wspierany przez Gson, twój problem może być rozwiązany za pomocą dwóch linii kodu!
JsonSurfer jsonSurfer = JsonSurfer.gson();
String result = jsonSurfer.collectOne(jsonLine, String.class, "$.data.translations[0].translatedText");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-12 06:07:40
Kod w jednej linii:
System.out.println(new Gson().fromJson(jsonLine,JsonObject.class).getAsJsonObject().get("data").getAsJsonObject().get("translations").getAsJsonArray().get(0).getAsJsonObject().get("translatedText").getAsString());
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-23 12:23:20
Jednym ze sposobów byłoby utworzenie JsonObject i iterację poprzez parametry. Na przykład
JsonObject jobj = new Gson().fromJson(jsonString, JsonObject.class);
Następnie można wyodrębnić wartości typu:
String fieldValue = jobj.get(fieldName).getAsString();
boolean fieldValue = jobj.get(fieldName).getAsBoolean();
int fieldValue = jobj.get(fieldName).getAsInt();
Mam nadzieję, że to pomoże.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-11 15:46:10