Getting object values from Json:
If you have a data in Json format and you need to retrieve the object values from that day, it can be easily done using Java.
Lets see an example,
If you are using maven add the following dependency:
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
or you can download the json-simple.jar file.
Suppose I have this data in Json:
{"name":"John","id":34,"age":56,"gender":"male"},
{"name":"Chris","id":35,"age":26,"gender":"male"}
So we will decode this in Java like this:
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class GetJson {
public static void main(String[] args) {
String s1="{\"name\":\"John\",\"id\":34,\"age\":56,\"gender\":\"male\"}"; // first record
Object ob1=JSONValue.parse(s1);
String s2="{\"name\":\"Chris\",\"id\":35,\"age\":26,\"gender\":\"male\"}"; //second record
Object ob2=JSONValue.parse(s2);
JSONObject json = (JSONObject) ob1;
String name = (String) json.get("name");
long id = (Long) json.get("id");
long age = (Long) json.get("age");
String gender = (String) json.get("gender");
System.out.println("Record1: "+name+" "+id+" "+age+" "+gender);
json = (JSONObject) ob2;
name = (String) json.get("name");
id = (Long) json.get("id");
age = (Long) json.get("age");
gender = (String) json.get("gender");
System.out.println("Record2: "+name+" "+id+" "+age+" "+gender);
}
}
Output:
Record1: John 34 56 male
Record2: Chris 35 26 male
We kept both records in the two String objects and then converted in to Json object and printed the corresponding values.
0 Comment(s)