Reputation: 3102
Here is my structure of json data. It has huge amount of data similarly to this. I am using Jackson parser for parsing this.
{
"dealers":
{
"google.com":{"id":1,"merchantname":"google","status":"active"},
"apple.com":{"id":2,"merchantname":"apple","status":"active"}
}
}
Code:
while (jParser.nextToken() != JsonToken.END_OBJECT) {
jParser.nextToken();
while (jParser.nextToken() != JsonToken.END_OBJECT) {
jParser.nextToken();
while (jParser.nextToken() != JsonToken.END_OBJECT) {
jParser.nextToken();
String fieldname = jParser.getCurrentName();
if (fieldname != null) {
if ("id".equals(fieldname)) {
jParser.nextToken();
if (jParser.getText() != null)
merchantID = jParser.getText();
else
merchantID = "";
}
if ("merchantname".equals(fieldname)) {
jParser.nextToken();
if (jParser.getText() != null)
merchantname = jParser.getText();
else
merchantname = "";
}
if ("status".equals(fieldname)) {
jParser.nextToken();
if (jParser.getText() != null)
name = jParser.getText();
}
}
}
}
}
The data is not parsed properly. Messed up with the jParser.nextToken() methods. Can anyone point out the mistake here?
Upvotes: 2
Views: 1321
Reputation: 38645
"dealers" property in JSON represents Map<String, POJO_CLASS>
. You can easily convert it to below POJO classes:
class RootEntity {
private Map<String, Entity> dealers;
//getters,setters, toString
}
class Entity {
private int id;
private String merchantname;
private String status;
//getters,setters, toString
}
Example usage:
import java.io.File;
import java.io.IOException;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonProgram {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.readValue(new File("/data/x.json"), RootEntity.class));
}
}
prints:
RootEntity [dealers={google.com=Entity [id=1, merchantname=google, status=active], apple.com=Entity [id=2, merchantname=apple, status=active]}]
Upvotes: 4