How can I use JsonParser (javax.json.stream.JsonParser) twice - java

I need to use a JsonParser twice, once to validate the format of my JsonStream by the json schema given..., then I need to contruct my object 'Product'.
The problem is that if I use the parser once, I cannot re-use it a second time. It's like it loses its data values .
Here is my Original code where I construct my Product object using the parser.. :
import javax.json.bind.serializer.DeserializationContext;
import javax.json.bind.serializer.JsonbDeserializer;
import javax.json.stream.JsonParser;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class ProductDeserializer implements JsonbDeserializer<Product>
{
#Override
public Product deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType)
{
Product product = new Product();
while (parser.hasNext())
{
JsonParser.Event event = parser.next();
if (event == JsonParser.Event.KEY_NAME && parser.getString().equals("productNumber"))
{
parser.next();
product.setProductNumber(parser.getString());
This works fine But I need to include this validation of the json format first..:
ObjectMapper objectMapper = new ObjectMapper();
JsonSchemaFactory schemaFactory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V201909);
String schemaStream = "My json schema here..";
JsonNode json = null;
try
{
json = objectMapper.readTree(parser.getObject().toString());
}
catch (JsonProcessingException eParam)
{
eParam.printStackTrace();
}
JsonSchema schema = schemaFactory.getSchema(schemaStream);
Set<ValidationMessage> validationResult = schema.validate(json);
if (validationResult.isEmpty()) {
System.out.println("no validation errors ");
} else {
System.out.println("There are validation errors ");
}
So if I try to include this part then the contruction of my Product Object will not work anymore and the Product will be null..
So my question is how can I use the parser twice in the same method ..
Thanks a lot in advance..

Related

How parse nested json in Spring

I have nested JSON with bunch of children objects, but I just need response_time and question, subquestions of survey_data. What is the best way to parse nested JSON in rest controller to the object in spring?
{
"is_test_data":false,
"language":"English",
"url_variables":{
"requestId":{
"key":"requestId",
"value":"1"
}
},
"response_time":1114,
"survey_data":{
"2":{
"id":2,
"type":"parent",
"question":"For each of the following factors, please rate your recent project",
"subquestions":{
"10":{
"10001":{
"id":10001,
"type":"MULTI_TEXTBOX",
"question":"Overall Quality : Rating",
"answer":null,
}
},
"11":{
"10001":{
"id":10001,
"type":"MULTI_TEXTBOX",
"question":"Achievement of Intended Objectives : Rating",
"answer":null
}
}
}
},
"33":{
"id":33,
"type":"HIDDEN",
"question":"Submitted",
"answer_id":0,
}
}
}
Thank you.
What you should do is parse the complete json to jsonObject using json-simple jar
which create a map like structure for the json and then you can simply get the desired value from it using the key as I explained in below example
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonDeserializer {
public static void main(String[] args) throws Exception {
File file = new File("test.json");
InputStream is = new FileInputStream(file);
StringBuilder textBuilder = new StringBuilder();
try (Reader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
textBuilder.append((char) c);
}
}
String jsonTxt = textBuilder.toString();
Object obj = new JSONParser().parse(jsonTxt);
JSONObject jo = (JSONObject) obj;
System.out.println(jo.get("response_time"));
}
}
JSON is a data communication format that is lightweight, text-based. Objects and arrays are two structured kinds that JSON can represent. A JSONArray may extract text from a String and convert it to a vector-like object. The getString(index) method of JSONArray can be used to parse a nested JSON object. This is a helper method for the getJSONString method (index). The getString() method returns a string.

Any possible ways to add a java code to existing java file programatically?

I have an interface and class file auto-generated using a custom maven plugin I created. The plugin will read the necessary data from a JSON file and create me a Java files using Jenesis4Java (Mojo code provided below).
REQUIREMENT - i have to traverse to the already generated file and add a new method or code in that file. Is there any way to achieve this from Mojo? Take a look at below generated code, so I have to add a new abstract method to it.
I can only regenerate the same file from beginning but not able to add to existing code.
The following code was generated-
/**
* Customer360 interface.
*/
import java.io.Serializable;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.*;
import reactor.core.publisher.Mono;
#Path(value = "/")
public interface Customer360 {
#GET
#Path(value = "")
#Produces(value = "application/json")
Mono<Response> casecreation(#Context
HttpHeaders httpHeaders, #Context
UriInfo uriInfo);
#GET
#Path(value = "")
#Produces(value = "application/json")
Mono<Response> getCustomerDetails(#Context
HttpHeaders httpHeaders, #Context
UriInfo uriInfo);
#GET
#Path(value = "")
#Produces(value = "application/json")
Mono<Response> prefetch(#Context
HttpHeaders httpHeaders, #Context
UriInfo uriInfo);
}
In the mojo file I have written the logic to generate this and another class file. (Mojo refers to java file in maven plugin creation process)
Mojo file for reference-
import net.sf.json.JSONSerializer;
import net.sourceforge.jenesis4java.*;
import net.sourceforge.jenesis4java.impl.MCodeWriter;
import net.sourceforge.jenesis4java.jaloppy.JenesisJalopyEncoder;
import org.apache.commons.io.IOUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import java.awt.*;
import java.io.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
//import reactor.core.publisher.Mono;
import java.util.Iterator;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.*;
#Mojo(name = "generate-code", defaultPhase = LifecyclePhase.COMPILE)
public class GenerateApiResource extends AbstractMojo {
#Parameter(defaultValue = "${project}", required = true, readonly = true)
MavenProject project;
#Parameter(defaultValue = "src/main/java", required = true)
protected File outputJavaDirectory;
#Parameter(defaultValue = "src/main/java", required = true)
protected File outputJavaDirectory2;
#Parameter
protected String[] endpoints;
private String apiName;
private AbstractMethod mtr;
private PackageClass cls ;
#Override
public void execute() throws MojoExecutionException, MojoFailureException {
this.apiName = endpoints[0];
System.out.println("API TO USE 1= >> "+apiName);
this.apiName = endpoints[1];
System.out.println("API TO USE 2= >> "+apiName);
this.apiName = "Customer360";
if (this.project != null) {
this.project.addCompileSourceRoot(this.outputJavaDirectory.getAbsolutePath());
this.project.addCompileSourceRoot(this.outputJavaDirectory2.getAbsolutePath());
}
/*if (!this.outputJavaDirectory.mkdirs()) {
getLog().error("Could not create source directory!");
} else {
}*/
try {
generateJavaCode();
} catch (IOException e) {
throw new MojoExecutionException("Could not generate Java source code!", e);
}
/*if (!this.outputJavaDirectory2.mkdirs()) {
getLog().error("Could not create source directory!");
} else {
} */
try {
generateJavaCode2();
} catch (IOException e) {
throw new MojoExecutionException("Could not generate Java source code!", e);
}
}
private void generateJavaCode2() throws IOException {
System.setProperty("jenesis.encoder", JenesisJalopyEncoder.class.getName());
// Get the VirtualMachine implementation.
VirtualMachine vm = VirtualMachine.getVirtualMachine();
// Instantiate a new CompilationUnit. The argument to the
// compilation unit is the "codebase" or directory where the
// compilation unit should be written.
// Make a new compilation unit rooted to the given sourcepath.
CompilationUnit unit = vm.newCompilationUnit(this.outputJavaDirectory2.getAbsolutePath());
// Set the package namespace.
unit.setNamespace("com.cs.frontline.apiimplementations");
unit.addImport("javax.inject.Inject");
unit.addImport("javax.ws.rs.core.Context");
unit.addImport("javax.ws.rs.core.HttpHeaders");
unit.addImport("javax.ws.rs.core.Response");
unit.addImport("javax.ws.rs.core.UriInfo");
unit.addImport("org.springframework.context.annotation.Scope");
unit.addImport("org.springframework.stereotype.Component");
unit.addImport(String.format("com.cs.frontoffice.api.%s",apiName));
unit.addImport("com.cs.frontoffice.dataorchestrationengine.EndPointHandler");
unit.addImport("reactor.core.publisher.Mono");
PackageClass cls = unit.newPublicClass(String.format("%sImpl",apiName));
cls.addImplements(String.format("%s",apiName));
unit.setComment(Comment.D, "The API Implementation class.");
cls.newField(vm.newType("EndPointHandler"),"endPointHandler").addAnnotation("Inject");
//READ FROM JSON FILE
JSONParser parser = new JSONParser();
JSONObject jsonObject;
JSONArray jsonArray;
try{
// parsing file
File file = new File(String.format("src/main/resources/%s.json",apiName));
jsonArray = (JSONArray) parser.parse(new FileReader(file));
for(Object obj: jsonArray){
JSONObject apiObj = (JSONObject) obj;
String operationId = (String) apiObj.get("operationId");
String method = (String) apiObj.get("method");
String endPointFunction = (String) apiObj.get("endPointFunction");
ClassMethod mtr = cls.newMethod(vm.newType("Mono<Response>"),operationId);
mtr.setAccess(Access.PUBLIC);
if(method == "POST" || method == "PUT"){
mtr.addParameter(vm.newType("String"),"requestBodyStr");
}
ClassType clsType = vm.newType("#Context HttpHeaders");
ClassType clsType2 = vm.newType("#Context UriInfo");
mtr.addParameter(clsType,"httpHeaders");
mtr.addParameter(clsType2,"uriInfo");
mtr.addAnnotation("Override");
Try tr = mtr.newTry();
tr.newCatch(vm.newType("Exception"),"e");
Let letx = tr.newLet(vm.newType("Mono<Response>"));
if(method.equals("GET")){
letx.addAssign("responseMap",vm.newInvoke("endPointHandler",String.format("%s",endPointFunction))
.addArg(vm.newVar("new Object() {}.getClass().getEnclosingMethod().getName()"))
.addArg(vm.newNull())
.addVarriableArg("uriInfo")
.addVarriableArg("httpHeaders"));
} else {
letx.addAssign("responseMap",vm.newInvoke("endPointHandler","getEndpointResponse")
.addArg(vm.newVar("new Object() {}.getClass().getEnclosingMethod().getName()"))
.addArg(vm.newVar("new JSONObject(requestBodyStr)"))
.addVarriableArg("uriInfo")
.addVarriableArg("httpHeaders"));
}
tr.newReturn().setExpression(vm.newVar("responseMap"));
mtr.newReturn().setExpression(vm.newNull());
}
} catch (Exception e){
System.out.println("File FAILED ======");
System.out.println(e);
}
unit.encode();
}
private void generateJavaCode() throws IOException {
System.setProperty("jenesis.encoder", JenesisJalopyEncoder.class.getName());
// Get the VirtualMachine implementation.
VirtualMachine vm = VirtualMachine.getVirtualMachine();
// Instantiate a new CompilationUnit. The argument to the
// compilation unit is the "codebase" or directory where the
// compilation unit should be written.
//
// Make a new compilation unit rooted to the given sourcepath.
CompilationUnit unit = vm.newCompilationUnit(this.outputJavaDirectory.getAbsolutePath());
// Set the package namespace.
unit.setNamespace("com.cs.frontoffice.api");
// Add an import statement for fun.
unit.addImport("java.io.Serializable");
unit.addImport("javax.ws.rs.GET");
unit.addImport("javax.ws.rs.Path");
unit.addImport("javax.ws.rs.Produces");
unit.addImport("javax.ws.rs.core.*");
unit.addImport("reactor.core.publisher.Mono");
// Comment the package with a javadoc (DocumentationComment).
unit.setComment(Comment.D, "Auto-Generated using the Jenesis Syntax API");
// Make a new interface.
Interface itr = unit.newPublicInterface(String.format("%s",apiName));
itr.addAnnotation("Path").addAnntationAttribute("value").setValue(vm.newString("/"));
// Comment the class with a javadoc (DocumentationComment).
unit.setComment(Comment.D, String.format("%s interface.",apiName));
ClassType t = vm.newType("Mono<Response>");
//READ FROM JSON FILE
JSONParser parser = new JSONParser();
JSONObject jsonObject;
JSONArray jsonArray;
try{
// parsing file
File file = new File(String.format("src/main/resources/%s.json",apiName));
jsonArray = (JSONArray) parser.parse(new FileReader(file));
for(Object obj: jsonArray){
JSONObject apiObj = (JSONObject) obj;
String operationId = (String) apiObj.get("operationId");
String path = (String) apiObj.get("path");
String method = (String) apiObj.get("method");
AbstractMethod mtr = itr.newMethod(vm.newType("Mono<Response>"),operationId);
mtr.addAnnotation(String.format("%s",method));
mtr.addAnnotation("Path").addAnntationAttribute("value").setValue(vm.newString(String.format("%s",path)));
mtr.addAnnotation("Produces").addAnntationAttribute("value").setValue(vm.newString("application/json"));
if(method.equals("POST") || method.equals("PUT")){
mtr.addParameter(vm.newType("#RequestBody String"),"requestBodyStr");
}
ClassType clsType = vm.newType("#Context HttpHeaders");
System.out.println(clsType.getName());
ClassType clsType2 = vm.newType("#Context UriInfo");
System.out.println(clsType.getName());
mtr.addParameter(clsType,"httpHeaders");
mtr.addParameter(clsType2,"uriInfo");
//Print interface
System.out.println(mtr);
}
} catch (Exception e){
System.out.println("File FAILED ======");
System.out.println(e);
}
// Write the java file.
unit.encode();
}
}
If you can represent your generated code in the Mojo as a String, you can easily edit it with Spoon. Let's say your generated code is in the String generatedCode, then the following will add an abstract method to it:
// create a Spoon model of the generated code
Launcher launcher = new Launcher();
VirtualFile virtualFile = new VirtualFile(generatedCode);
launcher.addInputResource(virtualFile);
launcher.buildModel();
CtInterface ctInterface = launcher.getModel().getRootPackage().getType("Customer360");
// create an abstract method
String codeWithAbstractMethod = "package pkg; abstract class AbstractClass { abstract void abstractMethod();} ";
CtClass<?> classWithAbstractMethod = Launcher.parseClass(codeWithAbstractMethod);
CtMethod abstractMethod = classWithAbstractMethod.getMethodsByName("abstractMethod").get(0);
// add abstract method to the generated code
ctInterface.addMethod(abstractMethod);
String prettyPrint = ctInterface.toString();
prettyPrint will hold a String representation of the transformed generated code. The abstract method here is only an example, Spoon has many useful tools for creating complex code elements which you can find in the documentation.

Map GeoJSON to Java with Jackson

I am trying to map a JSON file into Java objects using Jackson library. This json file is a multi-level file that can be found here:
https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson
It is the list of earthquakes that happened in the last 30 days in the US.
Here is the structure of this son file: https://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php
Now, I wrote a Java program that is reading fields from this file, specifically I am trying to access the field which is under features -> properties -> place (e.g. from the original file "place":"17km NW of Pinnacles, CA")). When I get to the properties field I can read it as a LinkedHashMap, but the next level, so the keys and values of this LinkedHashMap are being read as Strings:
for example this is one of the values : {type=Point, coordinates=[-121.2743333, 36.6375, 8.61]}
I WANT TO READ THESE VALUES AS ANOTHER OBJECT (NOT STRING, MAP MAYBE?) SO I COULD EXTRACT FURTHER DATA FROM IT.
Here is my class:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.ObjectMapper;
#JsonIgnoreProperties(ignoreUnknown = true)
public class ReadJSONFile {
private StringBuffer stringBuffer = new StringBuffer();
public void convert_json_to_java() throws Exception {
String url = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in .readLine()) != null) {
stringBuffer.append(inputLine);
stringBuffer.append("\n");
} in.close();
}
#SuppressWarnings("unchecked")
public void map_to_object() throws Exception {
ObjectMapper om = new ObjectMapper();
//ignore fields that are not formatted properly
om.configure(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Map<Object, Object> resultMap = om.readValue(stringBuffer.toString(), Map.class);
ArrayList<Object> featuresArrayList = (ArrayList<Object>) resultMap.get("features");
for(Object o : featuresArrayList) {
LinkedHashMap<Object, Object> propertiesMap = (LinkedHashMap<Object, Object>) o;
for(Map.Entry<Object, Object> entry : propertiesMap.entrySet()) {
//HERE IS THE PROBLEM, THE VALUES OF THIS MAP (SECOND OBJECT) IS BEING READ AS A STRING
//WHILE SOME VALUES ARE NOT A STRING:
//e.g. {type=Point, coordinates=[-121.2743333, 36.6375, 8.61]}
//AND I WANT TO READ IT AS A MAP OR ANY OTHER OBJECT THAT WOULD ALLOW ME TO ACCESS THE DATA
String propertiesMapValues = entry.getValue().toString();
}
}
}
}
Main.java
public class Main {
public static void main(String[] args) throws Exception {
ReadJSONFile rjf = new ReadJSONFile();
rjf.convert_json_to_java();
rjf.map_to_object();
}
}
Maven dependency: https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl
When I try casting this last object to anything else than String, the program gives me exception (can't cast String to another object). Did I do something wrong? Can someone tell me what can I do to access those fields without modifying Strings (e.g. splitting them into arrays etc.)?
Actually your code works but it could be a bit simplified. The method convert_json_to_java is unnecessary, you can pass the URL directly to the ObjectMapper.
The values in the map are not read as Strings, but you are converting them to Strings by calling toString(), which is defined for all objects. Acctual types can be Map, List, String, Integer etc., depending on the JSON content. Working with a generic map is indeed a bit annoying, so I would suggest you converting values to structured objects. GeoJSON is an open standard, so there are open-source libraries facilitating using it, e.g. geojson-jackson.
You would need to add a maven dependency:
<dependency>
<groupId>de.grundid.opendatalab</groupId>
<artifactId>geojson-jackson</artifactId>
<version>1.8.1</version>
</dependency>
Then the program could look something like:
import org.geojson.*
// ...
public class ReadJSONFile {
ObjectMapper om = new ObjectMapper();
public void mapToObject(String url) throws Exception {
Map<String, Object> resultMap = om.readValue(new URL(url), new TypeReference<Map<String, Object>>() {});
List<Feature> features = om.convertValue(resultMap.get("features"), new TypeReference<List<Feature>>() {});
for(Feature f : features) {
// Write the feature to the console to see how it looks like
System.out.println(om.writeValueAsString(f));
// Extract properties
Map<String,Object> properties = f.getProperties();
// ....
// Extract geometry
GeoJsonObject geometry = f.getGeometry();
if(geometry instanceof Point) {
Point p = (Point) geometry;
// do something with the point
} else if(geometry instanceof LineString) {
LineString mls = (LineString) geometry;
// ...
} else if(geometry instanceof MultiLineString) {
MultiLineString mls = (MultiLineString) geometry;
// ...
} else if(geometry instanceof MultiPoint) {
MultiPoint mp = (MultiPoint) geometry;
// ...
} else if(geometry instanceof Polygon) {
Polygon pl = (Polygon) geometry;
// ...
} else if(geometry != null) {
throw new RuntimeException("Unhandled geometry type: " + geometry.getClass().getName());
}
}
}
public static void main(String[] args) throws Exception {
ReadJSONFile rjf = new ReadJSONFile();
rjf.mapToObject("https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson");
}
}

How do I parse JSON objects from a JSONArray?

I have a very large JSON file in the following format:
[{"fullname": "name1", "id": "123"}, {"fullname": "name2", "id": "245"}, {"fullname": "name3", "id": "256"}]
It looks like a JSONArray. All the records are written in the same line.
Can you help me how can I parse this file using Java. I want to read each JSON object and display all the fullname and ids. Below is my attempt, but my code is not working:
import org.apache.commons.lang3.StringEscapeUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JSONFileReaderDriver {
public static void main(String[] args) throws FileNotFoundException,
IOException, ParseException
{
String filename="Aarau";
String src="C:\\"+filename+".json";
JSONParser parser = new JSONParser();
JSONObject obj;
try
{
BufferedReader br=new BufferedReader (new FileReader(src));
obj = (JSONObject) new JSONParser().parse(row);
String fullname=obj.get("fullname");
String id=obj.get("id");
System.out.println ("fullname: "+fullname+" id: "+id);
}catch(Exception e)
{e.printStackTrace();}
br.close();
}
}
Make your life easy and use an ObjectMapper.
This way you simply define a Pojo with the same properties as you json object.
In you case you need a Pojo that looks like this:
public class Person{
private String fullname;
private int id;
public Person(String fullname, int id) {
this.fullname = fullname;
this.id = id;
}
public String getFullname() {
return fullname;
}
public int getId() {
return id;
}
}
With that you only need to do:
ObjectMapper objectMapper = new ObjectMapper();
List<Person> persons = objectMapper.readValue(myInputStream, TypeFactory.defaultInstance().constructCollectionType(List.class, Person.class));
This is a hassle free and type safe approach.
Dependencies needed:
https://github.com/FasterXML/jackson-databind
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
you can use Json.simple java api , below is code that can helpful to you
byte[] bFile = Files.readAllBytes(new File("C:/xyz.json").toPath());
JSONArray root = (JSONArray) JSONValue.parseWithException(bFile);
JSONObject rootObj = (JSONObject) root.get(0);
You can get values from JSONObject based on key , it also depends on format of your json as there could be nested json data. So you have to extract data accordingly . Apart from this you can use jackson parser api or GSON as well.
Okay folks...just solved my problem. I am posting the solution in case someone runs into the same issue again, can use my solution. My solution is partly motivated by Rahul Rabhadiya. Thanks, dude.
try{
row=br.readLine();
JSONArray root = (JSONArray) JSONValue.parseWithException(row);
for (int i=0;i<root.size();i++)
{
JSONObject rootObj = (JSONObject) root.get(i);
String fullname=(String) rootObj.get("fullname");
System.out.println (fullname);
}
}catch(Exception e)
{
e.printStackTrace();
}
Your json is a JSONArray, so when you are parsing it, you need to parse it as a JSONArray.
JSONParser jsonParser = new JSONParser();
JSONArray a = (JSONArray) jsonParser.parse(new FileReader(src));
for (Object o : a) {
// access your object here.
}
I would suggest going with Jackson, in particular the Jackson Streaming API which is perfect for parsing large arrays like this.
See this answer: https://stackoverflow.com/a/24838392/3765428

How to read multiple JSON docs in single JSON file using Java?

I am new on JSON, I want to read the JSON document using device id, I have many document on single file, just like as a database:
{
"deviceType":"AccessPoint",
"transactionType":"response",
"messageType":"set_config",
"classes":[
{
"deviceType":"AccessPoint",
"classId":1,
"ipv4":"192.168.100.100",
"netmask":"192.168.100.100",
"ipv6":"192.168.100.100",
"className":"Interface",
"interfaceName":"wlan0",
"state":"UP",
"type":"wireless",
"deviceId":"1234",
"status":"waiting"
}
],
"deviceId":"1234",
"transactionId":"201675"
}
Sometimes, classes array contain multiple arrays like indexes [{},{},..].
So, how can I read the doc using search criteria with java web application.
Just out of curiosity , did something on Jackson (streaming parser , since there is mention of large number of elements). I am just doing an output as name : value , this can be logically enhanced to suit your tastes. This is not even close to production , but is a good start.
import java.io.FileInputStream;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
public class TestClass {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("yourpath/transactions.json")) {
JsonFactory jf = new JsonFactory();
JsonParser jp = jf.createParser(fis);
//System.out.println(JsonToken.START_ARRAY);
// jp.setCodec(new ObjectMapper());
jp.nextToken();
while (jp.hasCurrentToken()) {
if (jp.getCurrentToken().equals(JsonToken.START_OBJECT)
|| jp.getCurrentToken().equals(JsonToken.START_ARRAY)
|| jp.getCurrentToken().equals(JsonToken.END_ARRAY)
|| jp.getCurrentToken().equals(JsonToken.END_OBJECT)) {
} else {
System.out.print(jp.getText());
jp.nextToken();
System.out.print(":");
System.out.print(jp.getText());
System.out.println();
}
jp.nextToken();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Categories

Resources