JSON parsing - Reading Json Data
Json url- https://jsonplaceholder.typicode.com/users
Aim - Want to read Json data from this URL .
Step 1- Download - java-json.jar
Step 2- Create New Java Project and add this jar to your Project.
Step 3- write code :
import java.io.InputStream;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONArray;
import org.json.JSONObject;
public class EmployeeJSONParser {
public static void main(String[] args) {
String data="";
try{
URL u=new URL("https://jsonplaceholder.typicode.com/users");
HttpsURLConnection conn = (HttpsURLConnection)u.openConnection();
InputStream in = conn.getInputStream();
int ch;
while((ch=in.read())!=-1){
data=data+(char)ch;
}
}
catch(Exception e){
e.printStackTrace();
}
try{
JSONArray a=new JSONArray(data);
for (int i=0;i<a.length();i++){
JSONObject o=a.getJSONObject(i);
String name = o.getString("name");
System.out.println(name);
JSONObject o2 = o.getJSONObject("address");
System.out.println(o2.getString("city"));
}
}
catch(Exception e1){
e1.printStackTrace();
}
}
}
Aim - Want to read Json data from this URL .
Step 1- Download - java-json.jar
Step 2- Create New Java Project and add this jar to your Project.
Step 3- write code :
import java.io.InputStream;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONArray;
import org.json.JSONObject;
public class EmployeeJSONParser {
public static void main(String[] args) {
String data="";
try{
URL u=new URL("https://jsonplaceholder.typicode.com/users");
HttpsURLConnection conn = (HttpsURLConnection)u.openConnection();
InputStream in = conn.getInputStream();
int ch;
while((ch=in.read())!=-1){
data=data+(char)ch;
}
}
catch(Exception e){
e.printStackTrace();
}
try{
JSONArray a=new JSONArray(data);
for (int i=0;i<a.length();i++){
JSONObject o=a.getJSONObject(i);
String name = o.getString("name");
System.out.println(name);
JSONObject o2 = o.getJSONObject("address");
System.out.println(o2.getString("city"));
}
}
catch(Exception e1){
e1.printStackTrace();
}
}
}
Comments
Post a Comment