【问题标题】:Parsing JSON by GsonGson 解析 JSON
【发布时间】:2017-06-19 03:21:44
【问题描述】:

我有 JSON。实际上,我向您展示了我的 POJO 类,因为我的 JSON 喜欢它并且我想将 JSON 放入其中。 我看过来自 YouTube 和谷歌搜索的视频,但他们已经将所有信息 JSON 解析到他们的班级。不是属性 JSON 的一部分。

public class Earthquake {
List<Property> properties;

public List<Property> getProperties() {
    return properties;
}

public void setProperties(List<Property> properties) {
    this.properties = properties;
}
}

还有:

public class Property {

private String mMagnitude;
private String mLocation;
private long mDate;

public Property(String mMagnitude, String mLocation, long mDate) {
    this.mMagnitude = mMagnitude;
    this.mLocation = mLocation;
    this.mDate = mDate;
}

public String getmMagnitude() {
    return mMagnitude;
}

public String getmLocation() {
    return mLocation;
}

public long getmDate() {
    return mDate;
}
}

这是json online api。在我的实践中,我想将“功能”列表和“属性”对象中的一些信息放入我的地震 pojo 类中。如您所见,有一个属性属性列表。我只需要属性属性的“mag”、“place”、“time”。 我想用 JSON 解析这个 JSON,我该怎么做?

我用这种方式解析:

    List<Earthquake> earthquakes = new ArrayList<>();

    try {

        JSONObject baseJsonResponse = new JSONObject(earthQuakeJSON);
        JSONArray earthquakeArray = baseJsonResponse.optJSONArray("features");

        for (int i = 0; i < earthquakeArray.length(); i++) {
            JSONObject currentEarthquake = earthquakeArray.optJSONObject(i);
            JSONObject properties = currentEarthquake.optJSONObject("properties");
            String magnitude = properties.getString("mag");
            String location = properties.getString("place");
            long time = properties.getLong("time");
            Earthquake earthquake = new Earthquake(magnitude, location, time);
            earthquakes.add(earthquake);
        }

但是 Gson 怎么办呢?

【问题讨论】:

  • 你不要尝试改装,它有自己的转换器并且易于使用。另一个好处将减少样板代码和如此多的手动工作。你的代码会很容易阅读。
  • 看起来你甚至没有尝试过使用 Gson。请在发布您的问题之前这样做。
  • 我同意@cricket_007。这就是我开始 Json>GSON >Retrofit 的方式。从 Json 和 Gson 开始,可以很好地了解 json 解析的工作原理。在不使用 Gson 的情况下跳到 Retrofit 似乎是不健康的。

标签: android json gson


【解决方案1】:

根据 json 数据,我认为您以错误的方式使用 EarthQuake 和 Properties

  • 属性列表不需要具有 getter 和 setter 的 EarthQuake 对象
  • 您可以将 Properties 类重命名为 Earthquake,这将是我们要解析的实际列表。

public class Property {

    @SerializedName("mag")
    private String mMagnitude;

    @SerializedName("place")
    private String mLocation;

    @SerializedName("time")
    private long mDate;

    public Property(String mMagnitude, String mLocation, long mDate) {
        this.mMagnitude = mMagnitude;
        this.mLocation = mLocation;
        this.mDate = mDate;
    }

    public String getmMagnitude() {
        return mMagnitude;
    }

    public String getmLocation() {
        return mLocation;
    }

    public long getmDate() {
        return mDate;
    }
}

最后解析json用这个...

Gson gson = new Gson();
Type listOfEarthQuake= new TypeToken<List<Earthquake>>() {}.getType();
return gson.fromJson(earthQuakeString,listOfEarthQuake);

【讨论】:

  • JSON不包含字符串“mMagnitude”,所以这里需要Gson Property注解
  • 我使用了你的代码,但我怎样才能将这个 gson.fromJson(earthQuakeString,listOfEarthQuake) 传递给 recyclerview 适配器?我这样做link 但我得到了这个错误:Method threw java.lang.NullPointerException' exception. Cannot evaluate com.example.sayres.mygsonerthquake.HttpRequest$1.toString() 这是我的 GSON 方法:link。此方法返回 List
  • 这个链接可能会帮助你解析复杂的jsonjsonschema2pojo.org(设置源类型json,注释样式GSON)
  • @AmitBhandari 。它并不复杂。它只是 3 个属性的列表。也许我必须就这个问题再问一个问题。
  • @sayreskabir 由于您对 json 非常熟悉,GSON 也有同样的想法,但 GSON 不会从 jsobObject 收集原始数据,而是在内部处理它并在对象级别将数据交给我们。因此,如果您使用 jsonschema2pojo,它将给出您的 3 个属性实际所在的位置。不好的部分是您将创建一些包装器 pojo,它将您的实际 3 个属性保存在“属性”父属性下。或者您可以查看 gson 序列化器/反序列化器以获取更多信息。但我坚持当前状态下的第一个。
【解决方案2】:

我试过你的代码,但没有用:

如果对你有帮助,我做了一些改变:

地震

     import java.util.ArrayList;

    public class Earthquake {
    ArrayList<Property> properties= new ArrayList<Property>();

    public Earthquake(long t , long m , String p){
        Property pr = new Property(m ,p, t);
        properties.add(pr);
    }

}

属性

public class Property {

private long mMagnitude;
private String mLocation;
private long mDate;

public Property(long mMagnitude, String mLocation, long mDate) {
    this.mMagnitude = mMagnitude;
    this.mLocation = mLocation;
    this.mDate = mDate;
}


}

主要

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;


public class MainProp {

    public static void main(String[] args) throws JSONException {
        // TODO Auto-generated method stub



        List<Earthquake> earthquakes = new ArrayList<Earthquake>();
         List<Earthquake> fromjson = new ArrayList<Earthquake>();


            JSONParser jsp = new JSONParser();
            String url ="https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2016-01-01&endtime=2016-01-31&minmagnitude=6";
                JSONObject obj = jsp.makeHttpRequest(url, "GET");


            JSONArray earthquakeArray = obj.getJSONArray("features");//baseJsonResponse.optJSONArray("features");

            for (int i = 0; i < earthquakeArray.length(); i++) {
                JSONObject currentEarthquake = earthquakeArray.optJSONObject(i);
                JSONObject properties = currentEarthquake.optJSONObject("properties");
                Iterator<?> keys = properties.keys();

                long time =0;
                String location ="";
                long magnitude =0;
                Earthquake earthquake  = null;
                   while( keys.hasNext() ) {
                       String key = (String)keys.next();
                          if("time".equals(key))
                              time = properties.getLong("time");
                              if("place".equals(key))
                                   location = properties.getString("place");
                                  if("mag".equals(key)) 
                                       magnitude = properties.getLong("mag");

                                  if(!"".equals(location) && time !=0 && magnitude != 0){
                                      earthquake = new Earthquake(time,magnitude,location);
                                      earthquakes.add(earthquake);
                                  }
                          }

                   Gson gson = new Gson();
                      String json = gson.toJson(earthquake);
                      System.out.println(json);

                      Earthquake fromjsonItem =  gson.fromJson(json, Earthquake.class);

                       fromjson.add(fromjsonItem);


            }


        }

}

解析器 DefaultHttpClient 现已弃用:(

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    // constructor
    public JSONParser() {
    }
    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method) {
        // Making HTTP request
        try {
            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);  
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
         e.printStackTrace();
        }
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
             e.printStackTrace();
        }
        return jObj; 
    }
}

结果

【讨论】:

    猜你喜欢
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 2012-01-02
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多