我正试图在androidstudio中使用json为我的应用程序构建一个模拟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;
}
}
暂无答案!
目前还没有任何答案,快来回答吧!