我有一个字符串数据,我想将它添加到json并检索它以将其添加到excel。但它没有发生 请帮忙 这是我的代码......
String table = “[{” ID “:1,” 名称 “:” XXX “ ”位置“: ”XX“} { ”ID“:2 ”名称为“: ”YYY“, ”位置“: ”YY“} {” ID “:3”,名称为 “:” ZZZ “ ”位置“: ”ZZ“}]”;
JSONObject jObject = new JSONObject(table); // json String
projectname = jObject.getString("name"); // get the name from data.
System.out.println(projectname);
答案 0 :(得分:1)
您可以使用JSONObject和JsonArray,如下所示
JSONObject mainObj = new JSONObject();
JSONArray somearr = new JSONArray();
while (iter.hasnext()) {
ClassName someObject=iter.next();
JSONObject jsonobj = new JSONObject();
jsonobj.put("id", id_from_someObject);;
jsonobj.put("name", name_from_someObject);
jsonobj.put("name", location_from_someObject);;
somearr.put(seatObj);
}
mainObj.put("response",somearr);
return mainObj.toString();
答案 1 :(得分:1)
简单有效的方式我会告诉你使用json.org和jackson-mapper-asl首先创建一个类,假设它的名字是Person
public class Person {
private int id;
private String name;
private String location;
//getters and setters
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", location='" + location + '\'' +
'}';
}
}
创建另一个类假设mainclass
public static void main(String[] args) throws IOException, JSONException {
String jsonString ="[{\"id\":1,\"name\":\"xxx\",\"location\":\"xx\"},
{\"id\":2,\"name\":\"yyy\",\"location\":\"yy\"},
{\"id\":3,\"name\":\"zzz\",\"location\":\"zz\"}]";
ObjectMapper mapper = new ObjectMapper();
JSONArray jsonArray = new JSONArray(jsonString);
List<Person> listFromJsonArray = new ArrayList<Person>();
for(int i =0 ;i<jsonArray.length();i++){
String firstObjectAsString = jsonArray.get(i).toString();
Person person = mapper.readValue(mapper.readTree(firstObjectAsString),
Person.class);
listFromJsonArray.add(person);
}
System.out.println(listFromJsonArray);
}
现在使用列表获取单个Person对象,使用getter获取各个值并执行任何操作
答案 2 :(得分:0)
嗯,在定义表字符串时确实有错误。我猜猜你需要
String table = "[{'id':1,'name':'xxx','location':'xx'}{'id':2,'name':'yyy','location':'yy'}{'id':3,'name':'zzz','location':'zz'}]";
JSONObject jObject = new JSONObject(table);
而不是
String table = [{"id":1,"name":"xxx","location":"xx"}{"id":2,"name":"yyy","location":"yy"}{"id":3,"name":"zzz","location":"zz"}];
JSONObject jObject = new JSONObject(table);
答案 3 :(得分:0)
您可以尝试使用以下代码来解析json对象
String table = "{"keyElement" : {"id":1,"name":"xxx","location":"xx"}{"id":2,"name":"yyy","location":"yy"}{"id":3,"name":"zzz","location":"zz"}}";
JSONObject jObject = new JSONObject(table);
JSONArray array = jObject.getJSONArray("keyElement");
for(int i = 0 ; i < array.length() ; i++)
{
System.out.println(array.getJSONObject(i).getString("id"));
System.out.println(array.getJSONObject(i).getString("name"));
System.out.println(array.getJSONObject(i).getString("location"));
}
现在你可以了解......