反序列化嵌套的 JSON 到 Android Studio 中的 Java

huangapple 未分类评论96阅读模式
英文:

De-serializing nested JSON to Java in Android Studio

问题

我正在尝试将此JSON反序列化为Java对象类Mural的数组,并在我的应用程序中的列表(Recycler View)中显示它们。以下是我所需数据的格式化JSON示例。

{
"records": [{
	"recordid": "e6b10b2f7cadbe7caec9a0b36e9e7b570c3add50",
	"fields": {
		"auteur_s": "Dupa",
		"photo": {
			"id": "7cd8a2bc799826835057eaec21a28730"
			},
		"annee": "1994",
		"coordonnees_geographiques": [50.8527886675,
					      4.34530735016],
		"personnage_s": "Cubitus - Dommel"
		},
	},
	...
    ]
}

我使用Okhttp进行请求,并且响应成功,因此我使用它构造了一个JSONObject。我遍历该对象中的"records"数组,因为我在其中找到了所有需要的数据。具有字符串或数组值的键可以正常工作,我可以将它们加载到我的应用程序的Recycler View中,但是当我想访问"photo",即嵌套在另一个对象中的键值对时,我会收到JSONException org.json.JSONException: No value for photo,并且我的Recycler View返回为空。

以下是代码的示例:

private void fetchMurals(){
        threadExecutor.execute(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();

                Request request = new Request.Builder()
                        .url("https://bruxellesdata.opendatasoft.com/api/records/1.0/search/?dataset=comic-book-route&rows=58")
                        .get()
                        .build();
                try{ 
                    Response response = client.newCall(request).execute();
                    String json = response.body().string();

                    JSONObject jsonObject = new JSONObject(json);
                    JSONArray jsonRecordsArray = jsonObject.getJSONArray("records");

                    int arraySize = jsonRecordsArray.length();
                    muralArrayList = new ArrayList<>();

                    for (int i = 0; i < arraySize; i++){
                        String jsonID = jsonRecordsArray.getJSONObject(i).getString("recordid");
                        JSONObject jsonMural = jsonRecordsArray.getJSONObject(i).getJSONObject("fields");
                        JSONObject jsonMuralPhoto = jsonMural.getJSONObject("photo");

                        final Mural currentMural = new Mural(
                                jsonID,
                                (jsonMural.has("auteur_s")) ? jsonMural.getString("auteur_s") : "Unknown Author",
                                (jsonMuralPhoto.has("id")) ? jsonMuralPhoto.getString("id") : "No picture available!",
                                (jsonMural.has("personnage_s")) ? jsonMural.getString("personnage_s") : "Unknown character",
                                (jsonMural.has("annee")) ? jsonMural.getString("annee") : "Unknown year of creation",
                                new LatLng(jsonMural.getJSONArray("coordonnees_geographiques").getDouble(0),
                                           jsonMural.getJSONArray("coordonnees_geographiques").getDouble(1))
                        );
                        muralArrayList.add(currentMural);

                } catch (IOException e){
                    e.printStackTrace();
            }
        });
    }

我尝试过很多此类变体,但迄今为止都没有成功。是否可能是循环的问题?或者是我正在调用的jsonMural.getJSONObject("photo")出现了问题?

英文:

I'm trying to deserialize this JSON to an array of Java objects of class Mural and show them in a list (Recycler View) in my app. Here's formatted example of the JSON with only the data that I need.

{
&quot;records&quot;: [{ 
	&quot;recordid&quot;: &quot;e6b10b2f7cadbe7caec9a0b36e9e7b570c3add50&quot;, 
	&quot;fields&quot;: {
		&quot;auteur_s&quot;: &quot;Dupa&quot;, 
		&quot;photo&quot;: {
			&quot;id&quot;: &quot;7cd8a2bc799826835057eaec21a28730&quot;, 
			},
		&quot;annee&quot;: &quot;1994&quot;,
		&quot;coordonnees_geographiques&quot;: [50.8527886675, 
					      4.34530735016], 
		&quot;personnage_s&quot;: &quot;Cubitus - Dommel&quot;
		}, 
	},
	...
    ]
}

I use Okhttp to make the request and the response is successful, so I use it to construct a JSONObject.
I traverse the &quot;records&quot; array in that object, because that's where I find all the data I need. Keys that have a string or an array as value work fine and I can load them into my app's Recycler View, but when I want to access &quot;photo&quot;, i.e. a key:value pair nested within another object, I get a JSONException org.json.JSONException: No value for photo and my Recycler View returns empty.

Here's what the code looks like:

private void fetchMurals(){
        threadExecutor.execute(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();

                Request request = new Request.Builder()
                        .url(&quot;https://bruxellesdata.opendatasoft.com/api/records/1.0/search/?dataset=comic-book-route&amp;rows=58&quot;)
                        .get()
                        .build();
                try{ 
                    Response response = client.newCall(request).execute();
                    String json = response.body().string();

                    JSONObject jsonObject = new JSONObject(json);
                    JSONArray jsonRecordsArray = jsonObject.getJSONArray(&quot;records&quot;);

                    int arraySize = jsonRecordsArray.length();
                    muralArrayList = new ArrayList&lt;&gt;();

                    for (int i = 0; i &lt; arraySize; i++){
                        String jsonID = jsonRecordsArray.getJSONObject(i).getString(&quot;recordid&quot;);
                        JSONObject jsonMural = jsonRecordsArray.getJSONObject(i).getJSONObject(&quot;fields&quot;);
                        JSONObject jsonMuralPhoto = jsonMural.getJSONObject(&quot;photo&quot;);

                        final Mural currentMural = new Mural(
                                jsonID,
                                (jsonMural.has(&quot;auteur_s&quot;)) ? jsonMural.getString(&quot;auteur_s&quot;) : &quot;Unknown Author&quot;,
                                (jsonMuralPhoto.has(&quot;id&quot;)) ? jsonMuralPhoto.getString(&quot;id&quot;) : &quot;No picture available!&quot;,
                                (jsonMural.has(&quot;personnage_s&quot;)) ? jsonMural.getString(&quot;personnage_s&quot;) : &quot;Unknown character&quot;,
                                (jsonMural.has(&quot;annee&quot;)) ? jsonMural.getString(&quot;annee&quot;) : &quot;Unknown year of creation&quot;,
                                new LatLng(jsonMural.getJSONArray(&quot;coordonnees_geographiques&quot;).getDouble(0),
                                           jsonMural.getJSONArray(&quot;coordonnees_geographiques&quot;).getDouble(1))
                        );
                        muralArrayList.add(currentMural);

                } catch (IOException e){
                    e.printStackTrace();
            }
        });
    }

I've tried many variations of this but none have worked so far. Could it be a problem with my loop? Or with the jsonMural.getJSONObject(&quot;photo&quot;) that I am calling?

答案1

得分: 0

我现在明白,我当时是在检查我的记录是否有字段"id",而我应该检查它是否有"photo"。我在构造函数中将这一行代码更改为:

(jsonArtwork.has("photo")) ? jsonArtwork.getJSONObject("photo").getString("id") : "无可用图片!"

现在可以正常工作。

英文:

I see now that I was checking if my record had the field "id" whereas I should have been checking if it had "photo". I changed the line in my constructor to

(jsonArtwork.has(&quot;photo&quot;)) ? jsonArtwork.getJSONObject(&quot;photo&quot;).getString(&quot;id&quot;) : &quot;No picture available!&quot;

Works now.

huangapple
  • 本文由 发表于 2020年4月7日 06:41:48
  • 转载请务必保留本文链接:https://java.coder-hub.com/61070090.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定