Java 如何将数据从JSONObject接收到简单数组
我试图获取JSONObject中的int并将其放入字符串数组中,但我只能将其放入一个简单的字符串中 这就是JSONObjectJava 如何将数据从JSONObject接收到简单数组,java,android,arrays,json,Java,Android,Arrays,Json,我试图获取JSONObject中的int并将其放入字符串数组中,但我只能将其放入一个简单的字符串中 这就是JSONObject{“codigo”:2,“nome”:“teste2”} 这就是我可以将int从codigo传递到简单字符串的代码 String informacao; String code; String name[]; ListView listView; @Override public void onCreate(Bundle sav
{“codigo”:2,“nome”:“teste2”}
这就是我可以将int从codigo传递到简单字符串的代码
String informacao;
String code;
String name[];
ListView listView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
informacao = intent.getStringExtra("INFO");
try{
JSONObject jo = new JSONObject(informacao);
for (int i = 0; i < jo.length(); i++){
Log.i("ENTROU", "entrou");
code = jo.getString("codigo").toString();
Log.i("CODE!!!", code.toString());
}
} catch (JSONException e){
Log.i("ERRO", e.toString());
}
现在当我试着把它放到一个字符串数组中
String informacao;
String code[];
String name[];
ListView listView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
informacao = intent.getStringExtra("INFO");
try{
JSONObject jo = new JSONObject(informacao);
for (int i = 0; i < jo.length(); i++){
Log.i("ENTROU", "entrou");
code[i] = jo.getString("codigo").toString();
Log.i("CODE!!!", code[i].toString());
}
} catch (JSONException e){
Log.i("ERRO", e.toString());
}
您没有设置数组的长度。它不像JavaScript那样动态增加。如果按如下方式初始化数组:
stringcode[]=newstring[10]
您应该能够设置它的元素。那么问题在哪里呢?我如何使用我的字符串code[]
并将其大小设置为jo.length()
?因为我需要在另一个函数中使用它。如果你事先不知道大小,你可以使用List code=new ArrayList()然后只需添加如下元素:code.add(jo.getString(“codigo”).toString())代码>
String informacao;
String code[];
String name[];
ListView listView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
informacao = intent.getStringExtra("INFO");
try{
JSONObject jo = new JSONObject(informacao);
for (int i = 0; i < jo.length(); i++){
Log.i("ENTROU", "entrou");
code[i] = jo.getString("codigo").toString();
Log.i("CODE!!!", code[i].toString());
}
} catch (JSONException e){
Log.i("ERRO", e.toString());
}
2020-03-20 09:56:25.195 25695-25695/br.com.ifractal.Stou I/ENTROU: entrou