I am stucking with parse json in java. Here is my code:
package url.process;
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONAware;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class jsonArray implements JSONAware{
private long l;
public jsonArray(long l){
this.l=l;
}
public long getArray(){
return l;
}
public void setArray(long l){this.l=l;}
@Override
public String toJSONString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("\""+getArray()+"\"");
sb.append("}");
return sb.toString();
}
public static void main(String[] args){
// doc doi tuong thanh chuoi
List <jsonArray> listjsonarray = new ArrayList<jsonArray>(){
{
add( new jsonArray(76543456));
add( new jsonArray(112233445));
add( new jsonArray(546372));
add( new jsonArray(9876553));
}
};
System.out.println(JSONArray.toJSONString(listjsonarray));
//doc chuoi thanh doi tuong
String jsonString = "[{\"76543456\"},"+"{\"112233445\"},"+"{\"546372\"},"+"{\"9876553\"}]";
try{
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(jsonString);
for(int i =0;i<jsonArray.size();i++){
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
long l = Long.parseLong((String) jsonObject.get("l"));
jsonArray ja = new jsonArray(l);
System.out.println("Elements is "+ja.getArray());
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
The result is : [{"76543456"},{"112233445"},{"546372"},{"9876553"}] null
I do not know to parse this array above. Please help me, thank you so much and have a good time.
Your JSON is invalid. Braces {}
indicate a JSON object which contains key-value pairs. But you are putting JSON strings in them.
[{"76543456"},{"112233445"},{"546372"},{"9876553"}]
Perhaps you meant to have
["76543456","112233445","546372","9876553"]
The JSON format is described here .
You'll have other problems later when trying to cast a String
to a JSONObject
. Handle those appropriately. If you're storing JSON strings, you should get back Java String
objects.
JSON is a key value data structure. For example, a JSON object is as follow:
{"name" : "John Smith"}
The string you input there doesn't follow the convention of JSON, therefore the program couldn't work
The null
output is because of
}catch(Exception e){
System.out.println(e.getMessage());
});
The json is not valid and therefore you get a ParseException
and this exception has no message.
As I can see you want to get the l
property of the JSONObject
long l = Long.parseLong((String) jsonObject.get("l"));
in this case the correct json would be
String jsonString = "[{\"l\": \"76543456\"},"+"{\"l\": \"112233445\"},"+"{\"l\": \"546372\"},"+"{\"l\": \"9876553\"}]";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.