从Json Array获取特定值

时间:2015-04-11 09:30:45

标签: java php android mysql json

你好吗

我需要访问一个数据库并从表中读取数据然后获取它的值,所以我创建一个php文件来打印一个JSON格式的数据库来访问数据:

<?php
try{
    $db=new PDO('mysql:host=localhost;dbname='database','table','password');
    $row=$db->prepare('select * from users' );
    $row->execute();
    $json_data=array();
    foreach($row as $rec)
    {
        $json_array['userId']=$rec['userId'];
        $json_array['user']=$rec['user'];
        $json_array['pass']=$rec['pass'];
        $json_array['name']=$rec['name'];
        $json_array['family']=$rec['family'];
        $json_array['gender']=$rec['gender'];
        $json_array['birthday']=$rec['birthday'];

        array_push($json_data,$json_array);
    }
    echo json_encode($json_data);
} catch(PDOExcetion $e)
{
    print "Error: " . $e->getMessage()."<br/>";
    die();
}
?>

这是输出:

[
    {"userId":"1","user":"saly","pass":"666","name":"SalyR","family":"manson","gender":"male","birthday":"1988\/11\/10"},
    {"userId":"1","user":"foo","pass":"2657","name":"foo","family":"rocki","gender":"male","birthday":"13989\/2\/07"},
    {"userId":"1","user":"mil","pass":"63495","name":"milo","family":"toufa","gender":"male","birthday":"13987\/04\/21"},
    {"userId":"1","user":"soos","pass":"03468","name":"soro","family":"radi","gender":"female","birthday":"13990\/08\/09"}
]

我想访问指定的值,例如&#39; userId&#39;和&#39; name&#39;和生日&#39;

我使用三种方法来获取值:

1) getJSONFromDatabase 方法获取数据库URL并返回JSON字符串。

public String getJSONFromDatabase(String getDatabaseURL) {
        HttpClient client = new DefaultHttpClient();
        HttpPost method = new HttpPost(getDatabaseURL);
        String result = "";

        try {
            HttpResponse response = client.execute(method);
            int code = response.getStatusLine().getStatusCode();
            InputStream stream = response.getEntity().getContent();
            result = inputstreamToString(stream);
            Log.i("LOG", "Code :" + code);
        } catch (IOException e) {
            Log.e("Database", "Error Connect to Database!");
            e.printStackTrace();
        }
        return result;
    }

2) inputstreamToString 方法获取一个Inputstream并读取所有行。

private String inputstreamToString(InputStream getStream) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(getStream));
        StringBuilder builder = new StringBuilder();
        String line;

        try {
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            return builder.toString();
        } catch (IOException e) {
            Log.e("Reader", "Error reading stream!");
            e.printStackTrace();
        }
        return "";
    }

3) jsonToString 方法获取带有我们想要的String值的JSON String。

public String jsonToString(String getJSONString, String value) {
        String userId = "";
        try {
            JSONObject object = new JSONObject(getJSONString);
            userId = object.getString(value);
            return userId;

        } catch (JSONException e) {
            Log.e("JSON", "Error converting!");
            e.printStackTrace();
        }
        return "";
    }

所以我称之为这样的方法:

String databaseURL = "http://192.168.56.1/saly/getDatabaseTable.php";
String jsonFormat = getJSONFromDatabase(databaseURL);
String userId = jsonToString(jsonFormat, "userId");
String name= jsonToString(jsonFormat, "name");
String birthday= jsonToString(jsonFormat, "birthday");

最后我在Log中遇到了这个错误:

JSON: Error converting!  

JSON: Error converting!  

JSON: Error converting!

当我删除 [] 并写一行就像这个JSON字符串一样,它正常工作,只有一行!

{
    "userId":"1",
    "user":"saly",
    "pass":"666",
    "name":"SalyR",
    "family":"manson",
    "gender":"male",
    "birthday":"1988\/11\/10"
}

但它不适合我,因为当我以JSON格式打印所有数据库表时,将打印整个数据。

我写了太多而且对不起,我试着解释每一件事。 如果我错了,请你帮我吗?

谢谢。

2 个答案:

答案 0 :(得分:1)

您必须将其解析为jsonArray。以下片段将对您有所帮助。

JSONArray jsonarray = new JSONArray(str);//str= your json string.


for(int i=0; i<jsonarray.length(); i++){
    JSONObject obj = jsonarray.getJSONObject(i);

    String name = obj.getString("name");
    String url = obj.getString("url");

    System.out.println(name);
    System.out.println(url);
}   

Here就是这个问题的答案。

答案 1 :(得分:1)

User.java

它是用户类。

public class User {

private String userId = "";
private String user = "";
private String pass = "";
private String name = "";
private String family = "";
private String gender = "";
private String birthday = "";

public String getUserId() {
    return userId;
}
public void setUserId(String userId) {
    this.userId = userId;
}
public String getUser() {
    return user;
}
public void setUser(String user) {
    this.user = user;
}
public String getPass() {
    return pass;
}
public void setPass(String pass) {
    this.pass = pass;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getFamily() {
    return family;
}
public void setFamily(String family) {
    this.family = family;
}
public String getGender() {
    return gender;
}
public void setGender(String gender) {
    this.gender = gender;
}
public String getBirthday() {
    return birthday;
}
public void setBirthday(String birthday) {
    this.birthday = birthday;
}

@Override
public String toString() {
    // TODO Auto-generated method stub
    return userId+" "+user+ " "+pass+ " "+name+" "+family+" "+ gender+ " "+ " ";
}


}

您可以将其作为测试运行,此示例显示使用Gson库处理JSON是多么容易

public class SIx {

public static void main(String[] args) {

    ArrayList<User> list = new ArrayList<User>();

    System.out.println("#### Object ####");

    for (int i = 0; i < 4; i++) {
        User user = new User();
        user.setUserId("UserId_"+i);
        user.setUser("User_"+i);
        user.setPass("Pass_"+i);
        user.setName("Name_"+i);
        user.setGender("Gender_"+i);
        user.setFamily("Family_"+i);
        user.setBirthday("Birthday_"+i);
        list.add(user);
        System.out.println(user.toString());
    }

    String string = (new Gson()).toJson(list);

    System.out.println();
    System.out.println();

    System.out.println(string);

    System.out.println();
    System.out.println();

    ArrayList<User> newList = (new Gson()).fromJson(string,  new TypeToken<ArrayList<User>>() {}.getType());

    for (int i = 0; i < newList.size(); i++) {
        User user = newList.get(i);
        System.out.println("UserId_:  "+user.getUserId());
        System.out.println("User_:  "+user.getUser());
        System.out.println("Pass_:  "+user.getPass());
        System.out.println("Name_:  "+user.getName());
        System.out.println("Gender_:  "+user.getGender());
        System.out.println("Family_:  "+user.getFamily());
        System.out.println("Birthday_:  "+user.getBirthday());
        System.out.println();
    }

}
}

输出

enter image description here