Skip to content

Instantly share code, notes, and snippets.

@biswarupadhikari
Created July 22, 2012 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biswarupadhikari/3160617 to your computer and use it in GitHub Desktop.
Save biswarupadhikari/3160617 to your computer and use it in GitHub Desktop.
How Parse PHP JSON DATA BY JAVA
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
public class API {
private String webPageUrl="";
public API(String URL){
this.webPageUrl=URL;
}
public String getContent(){
StringBuilder sb=new StringBuilder();
try {
URL url=new URL(this.webPageUrl);
InputStream stream=url.openStream();
BufferedInputStream bf=new BufferedInputStream(stream);
while (true) {
int data=bf.read();
if(data==-1){
break;
}else{
sb.append((char)data);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
http://localhost/API/API.java
<?php
$array=array();
$user['uid']=121;
$user['username']="adidac";
$user['password']="adidacpass";
$array['users'][]=$user;
$user['uid']=122;
$user['username']="biswarup";
$user['password']="biswaruppass";
$array['users'][]=$user;
$user['uid']=123;
$user['username']="gopal";
$user['password']="gopalpass";
$array['users'][]=$user;
echo json_encode($array);
import com.google.gson.Gson;
public class jsonex {
public static void main(String[] args) {
API API=new API("http://localhost/api/api.php");
String MyJson=API.getContent();
Gson gson = new Gson();
Users a=gson.fromJson(MyJson, Users.class);
User u=new User();
for (int i = 0; i <a.getUsers().size(); i++) {
u=a.getUsers().get(i);
System.out.println(u.getUid());
System.out.println(u.getUsername());
System.out.println(u.getPassword());
}
}
}
121
adidac
adidacpass
122
biswarup
biswaruppass
123
gopal
gopalpass
public class User {
private int uid;
private String username;
private String password;
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
import java.util.ArrayList;
public class Users {
private ArrayList<User> users = new ArrayList<User>();
public void setUsers(User user) {
users.add(user);
}
public ArrayList<User> getUsers() {
return users;
}
}
@biswarupadhikari
Copy link
Author

Download google-gson Java Library
http://code.google.com/p/google-gson/downloads/list

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment