我是android的新手,我在下面给出了结构中的json。如何使用json解析或改造来解析?
{
"1,abcd":[{
"v_id":"1"
}]
"2,efgh":[{
"v_id":"2"
}]
}
答案 0 :(得分:1)
试试这个
try {
JSONObject jsonObject = new JSONObject("yourresponce");
JSONArray jsonarray = jsonObject.getJSONArray("1,abcd");
for(int i=0;i<jsonarray.length();i++){
JSONObject jsonObject1 = jsonarray.getJSONObject(i);
String v_id = jsonObject1.getString("v_id");
Log.d("seelogcat","values "+v_id);
}
JSONArray jsonarray2 = jsonObject.getJSONArray("2,efgh");
for(int i=0;i<jsonarray2.length();i++){
JSONObject jsonObject1 = jsonarray2.getJSONObject(i);
String v_id = jsonObject1.getString("v_id");
Log.d("seelogcat","values "+v_id);
}
}catch (Exception e){
}
您的json格式无效:您的格式应该低于此
{
"1,abcd": [{
"v_id": "1"
}], // here you have to add (,)
"2,efgh": [{
"v_id": "2"
}]
}
您可以在此查看您的Json是否有效https://jsonlint.com/
要将密钥分开:
Iterator<?> keys = response.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( jObject.get(key) instanceof JSONObject ) {
System.out.println(key); // here you need splint based on (,)
}
}
答案 1 :(得分:1)
那里有一个逗号(,)丢失。签入jsonlint
{
"1,abcd": [{
"v_id": "1"
}],
"2,efgh": [{
"v_id": "2"
}]
}
Gson的改造可以完成剩下的工作。响应的POJO如下:
public class Example {
@SerializedName("1,abcd")
@Expose
private List<_1Abcd> Abcd = null;
@SerializedName("2,efgh")
@Expose
private List<_2Efgh> Efgh = null;
public List<_1Abcd> get1Abcd() {
return Abcd;
}
public void set1Abcd(List<_1Abcd> Abcd) {
this.Abcd = Abcd;
}
public List<_2Efgh> get2Efgh() {
return Efgh;
}
public void set2Efgh(List<_2Efgh> Efgh) {
this.Efgh = Efgh;
}
}
和
public class _1Abcd {
@SerializedName("v_id")
@Expose
private String vId;
public String getVId() {
return vId;
}
public void setVId(String vId) {
this.vId = vId;
}
}
和
public class _2Efgh {
@SerializedName("v_id")
@Expose
private String vId;
public String getVId() {
return vId;
}
public void setVId(String vId) {
this.vId = vId;
}
}