如何根据Android Studio中JSON对象中的另一个值从JSON文件中获取特定值 - Java

Posted

技术标签:

【中文标题】如何根据Android Studio中JSON对象中的另一个值从JSON文件中获取特定值 - Java【英文标题】:How to get a specific value from a JSON file based on another value in the JSON object in Android Studio - Java 【发布时间】:2021-07-19 01:32:55 【问题描述】:

我正在尝试使用 JSON 在 android Studio 中为我的应用程序组合一个 Mock API,并且我正在尝试找出如何从 JSON 文件中获取特定值?

例如,我想从数组“horoscopes”中获取“horoscope”字符串,其中“sunsign”字符串等于“aries”。

这可能非常简单,但我不太确定从哪里开始。

这是我的 JSON:

  "horoscopes": [
    
      "horoscopeId": 1,
      "sunsign": "aquarius",
      "month": "january",
      "horoscope": "I am the january horoscope for aquarius",
    ,
    
      "horoscopeId": 2,
      "sunsign": "pisces",
      "month": "january",
      "horoscope": "I am the january horoscope for pisces",
    ,
    
      "horoscopeId": 3,
      "sunsign": "aries",
      "month": "january",
      "horoscope": "I am the january horoscope for aries",
    ,
    
      "horoscopeId": 4,
      "sunsign": "taurus",
      "month": "january",
      "horoscope": "I am the january horoscope for taurus",
    ,
    
      "horoscopeId": 5,
      "sunsign": "gemini",
      "month": "january",
      "horoscope": "I am the january horoscope for gemini",
    ,
    
      "horoscopeId": 6,
      "sunsign": "cancer",
      "month": "january",
      "horoscope": "I am the january horoscope for cancer",
    ,
    
      "horoscopeId": 7,
      "sunsign": "leo",
      "month": "january",
      "horoscope": "I am the january horoscope for leo",
    ,
    
      "horoscopeId": 8,
      "sunsign": "virgo",
      "month": "january",
      "horoscope": "I am the january horoscope for virgo",
    ,
    
      "horoscopeId": 9,
      "sunsign": "libra",
      "month": "january",
      "horoscope": "I am the january horoscope for libra",
    ,
    
      "horoscopeId": 10,
      "sunsign": "scorpio",
      "month": "january",
      "horoscope": "I am the january horoscope for scorpio",
    ,
    
      "horoscopeId": 11,
      "sunsign": "sagittarius",
      "month": "january",
      "horoscope": "I am the january horoscope for sagittarius",
    ,
    
      "horoscopeId": 12,
      "sunsign": "capricorn",
      "month": "january",
      "horoscope": "I am the january horoscope for capricorn",
    
 ]

这是我到目前为止连接到 JSON 的内容:


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

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

public class horoscope extends AppCompatActivity 

    ArrayList<String> horoscope_al = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_horoscope);

        
        try 
            JSONObject obj = new JSONObject(loadJSONFromAsset());
            JSONArray horoscopeArray = obj.getJSONArray("horoscopes");
            for (int i = 0; i < horoscopeArray.length(); i++) 
                JSONObject horoscopeValues = horoscopeArray.getJSONObject(i);
                horoscope_al.add(horoscopeValues.getString("horoscope"));
            
         catch (JSONException e) 
            e.printStackTrace();
        
    

    public String loadJSONFromAsset()
    
        String json_string = null;
        try 
            InputStream inpSt = getAssets().open("horoscope_api.json");
            int s = inpSt.available();
            byte[] buffer_byte = new byte[s];
            inpSt.read(buffer_byte);
            inpSt.close();
            json_string = new String(buffer_byte, "UTF-8");
         catch (IOException ex) 
            ex.printStackTrace();
            return null;
        
        return json_string;
    

更新代码

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

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

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class horoscope extends AppCompatActivity 

    Button back_btn;
    TextView horoscope_txt;
    String al_string = " ";

    ArrayList<String> horoscope_al = new ArrayList<>();
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_horoscope);

        horoscope_txt = (TextView)findViewById(R.id.horoscope_txt);
        back_btn = (Button)findViewById(R.id.back_btn);
        back_btn.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                Intent back_intent = new Intent(horoscope.this, menu.class);
                startActivity(back_intent);
            
        );


       try 
            JSONObject obj = new JSONObject(loadJSONFromAsset());
            JSONArray horoscopeArray = obj.getJSONArray("horoscopes");

            List<String> horoscopesOfAries = IntStream.range(0, horoscopeArray.length())
                    .mapToObj(horoscopeArray::getJSONObject)
                    .filter(horoscopeJson -> horoscopeJson.getString("sunsign").equals("aries"))
                    .map(horoscopeJson -> horoscopeJson.getString("horoscope"))
                    .collect(Collectors.toList());

            /*for (int i = 0; i < horoscopeArray.length(); i++) 
                JSONObject horoscopeValues = horoscopeArray.getJSONObject(i);
                horoscope_al.add(horoscopeValues.getString("horoscope"));
                al_string += horoscope_al.get(i);
            */
         catch (JSONException e) 
            e.printStackTrace();
        

        //horoscope_txt.setText(al_string);
    

    public String loadJSONFromAsset()
    
        String json_string = null;
        try 
            InputStream inpSt = getAssets().open("horoscope_api.json");
            int s = inpSt.available();
            byte[] buffer_byte = new byte[s];
            inpSt.read(buffer_byte);
            inpSt.close();
            json_string = new String(buffer_byte, "UTF-8");
         catch (IOException ex) 
            ex.printStackTrace();
            return null;
        
        return json_string;
    

【问题讨论】:

【参考方案1】:

您可以执行以下操作:

JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray horoscopeArray = obj.getJSONArray("horoscopes");

List<String> horoscopesOfAries = IntStream.range(0, horoscopeArray.length())
        .mapToObj(horoscopeArray::getJSONObject)
        .filter(horoscopeJson -> horoscopeJson.getString("sunsign").equals("aries"))
        .map(horoscopeJson -> horoscopeJson.getString("horoscope"))
        .collect(Collectors.toList());

输出:

[I am the january horoscope for aries]

【讨论】:

非常感谢您!唯一的问题是“mapToObj(horoscopeArray::getJSONObject)”位抛出一个错误说“未处理的异常:org.json.JSONException”,你知道是什么原因造成的吗? @ells99 我认为 JSON 开头缺少一个“”。添加后,我得到了那个输出。您可以使用此工具确保 JSON - jsonlint.com 啊,是的,谢谢,我认为这是我的垃圾复制和粘贴:/ 我刚刚用该工具检查了我的 JSON,它都是有效的,但错误仍然存​​在,所以我不是太确定还有什么可能导致它 @ells99 是否详细说明了错误?这一行只是数组中每个 json 的 horoscopeArray.getJSONObject(i) 啊,好吧,它说“返回索引处的值,如果它存在并且是 JSONObject。抛出 org.json.JSONException - 如果值不存在或不是 JSONObject。”但它已经在尝试捕获?

以上是关于如何根据Android Studio中JSON对象中的另一个值从JSON文件中获取特定值 - Java的主要内容,如果未能解决你的问题,请参考以下文章

如何根据用户在Android Studio(Java)中输入的条件显示可绘制对象

当JSON对象URL字段在android studio中包含多个URL时,如何存储来自JSON对象请求的URL?

Android studio解析json对象

尝试从 Android Studio 中的 json 对象中检索 json 值

在 android Studio 中迭代包含列表/数组的 JSON 对象

如何访问数组改造 2 / android studio 中的对象“播放器”