[英]How to convert JSON Array integer variable to string
I am having issues parsing my integer values from JSON to String so I can add it to an array list. 我在将我的整数值从JSON解析为String时遇到问题,因此我可以将其添加到数组列表中。
I have tried using Integer.valueOf
but I am a bit stuck on the formatting for this particular issue and whether Integer.valueOf
will actually work or not. 我曾尝试使用Integer.valueOf
但对于此特定问题以及Integer.valueOf
是否会实际工作,在格式设置上有些卡住。
This is the code I have that works so far 这是我到目前为止可以使用的代码
try {
JSONArray jsonArray = new JSONArray(response);
vehicleMakes = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
String make = jsonArray.getJSONObject(i).get("make").toString();
String model = jsonArray.getJSONObject(i).get("model").toString();
String reg = jsonArray.getJSONObject(i).get("license_number").toString();
// int year = jsonArray.getJSONObject(i).get("year").toString();
Vehicle V = new Vehicle(make, model, reg);
vehicleArrayList.add(V);
}
}
catch (JSONException e) {
e.printStackTrace();
}
I am trying to add integer variables with this, such as 我试图与此添加整数变量,例如
int year = jsonArray.getJSONObject(i).get("year").toString();
How can I add this? 如何添加呢?
int year = jsonArray.getJSONObject(i).getInt("year");
String strYear = String.valueOf(year);
Use this. 用这个。
我不确定您使用的是什么库,但是如果是org.json,则可以尝试如下操作:
int year = jsonArray.getJSONObject(i).getInt("year");
Take a closer look at this line: 仔细看看这一行:
int year = jsonArray.getJSONObject(i).get("year").toString();
Your trying to add an integer and a string, as java is a typed language this wont work and youll likely get a compile time error flagged by the compiler, to resolve this youve got a few options, my suggestion is this: 您尝试添加整数和字符串,因为java是无法正常工作的类型化语言,并且您可能会收到编译器标记的编译时错误,为解决此问题,您有几个选择,我的建议是:
int result = Integer.parseInt(yourString) // good option, will account for ascii codes ang give you the correct value
// now convert to a string like so:
String.valueOf(result);
// so your code would be:
int year = Integer.parseInt(jsonArray.getJSONObject(i).get("year").toString());
You can convert String to int with 您可以将String转换为int
Integer.parseInt(string);
Integer.parseInt(jsonArray.getJSONObject(i).get("year").toString());
public static String[] toStringArray(JSONArray array) {
if(array==null)
return null;
String[] arr=new String[array.length()];
for(int i=0; i<arr.length; i++) {
arr[i]=array.optString(i);
}
return arr;
}
If compiler doesn't recognise this way, add org.json library. 如果编译器无法识别这种方式,请添加org.json库。
Example: 例:
String year = String.valueOf(jsonObject.getInt("year"));
or in your case: 或者您的情况:
String year = String.valueOf(jsonArray.getJSONObject(i).getInt("year"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.