使用GSON从JSON获取数组及其对象

时间:2019-01-31 10:40:24

标签: java gson

我有这个字符串:

import { Component, OnInit, DoCheck } from "@angular/core";

import { AuthService } from "src/app/services/auth.service";

import { User } from "src/app/models/User";

import { LoginService } from "src/app/services/login.service";

@Component({
  selector: "app-sidebar",
  templateUrl: "./sidebar.component.html",
  styleUrls: ["./sidebar.component.css"]
})
export class SidebarComponent implements OnInit, DoCheck {
isSidenavOpen: boolean = true;
user: User;
loggin$: Subscription;
logout$: Subscription;

  constructor(private _authService: AuthService, private _loginService: LoginService) {
    this.loggin$ = this._loginService.userLoggin.subscribe(user => {
      this.user = user;
    });

    this.logout$ = this._loginService.userLoggout.subscribe(user => {
      this.user = null;
    });
  }

  ngOnInit() {
  }

  ngOnDestroy() {
    this.loggin$.unsubscribe();
    this.logout$.unsubscribe();
  }
}

这是一个JSON,我做了这个类来获取数据

{"cod":"200","message":0.0049,"cnt":40,"list":[{"dt":1549346400,"main":{"temp":-1.04,"temp_min":-1.04,"temp_max":-1.04,"pressure":1023.46,"sea_level":1025.98,"grnd_level":1023.46,"humidity":92,"temp_kf":0},"weather":[{"id":600,"main":"Snow","description":"небольшой снегопад","icon":"13n"}],"clouds":{"all":80},"wind":{"speed":3.26,"deg":226.502},"rain":{},"snow":{"3h":1.485},"sys":{"pod":"n"},"dt_txt":"2019-02-05 06:00:00"},{"dt":1549357200,"main":{"temp":-1.04,"temp_min":-1.04,"temp_max":-1.04,"pressure":1023.78,"sea_level":1026.44,"grnd_level":1023.78,"humidity":95,"temp_kf":0},"weather":[{"id":600,"main":"Snow","description":"небольшой снегопад","icon":"13d"}],"clouds":{"all":80},"wind":{"speed":5.32,"deg":243.5},"rain":{},"snow":{"3h":1.115},"sys":{"pod":"d"},"dt_txt":"2019-02-05 09:00:00"}],"city":{"id":536203,"name":"Sankt-Peterburg","coord":{"lat":59.9167,"lon":30.25},"country":"RU"}}

因此,我还需要从此字符串中获取有关天气(温度,湿度,描述和风)的数据,该数据位于第一个dt“ 1549346400”中的数组“ list”中。我做了一个JSON数组,并把“列表”作为JSONArray。是的,我从列表“ dt 1549346400”中获取了JSONObject,并使用吸气剂获取数据。

现在,我需要使用Google GSON做同样的事情。阅读github上的指南,但仍然不了解如何从JSON获取0索引数据。

1 个答案:

答案 0 :(得分:0)

String jsonStr = "{}";

Gson gson = new Gson();
JsonElement element = gson.fromJson (jsonStr, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();