Split a large JSON file into smaller JSON files using Java - java

I have a large dataset in JSON format, for ease of use, I want to split it into multiple json files while still maintaining the structure.
For ex:{
"{"users": [
{
"userId": 1,
"firstName": "Krish",
"lastName": "Lee",
"phoneNumber": "123456",
"emailAddress": "krish.lee#learningcontainer.com"
},
{
"userId": 2,
"firstName": "racks",
"lastName": "jacson",
"phoneNumber": "123456",
"emailAddress": "racks.jacson#learningcontainer.com"
},
{
"userId": 3,
"firstName": "denial",
"lastName": "roast",
"phoneNumber": "33333333",
"emailAddress": "denial.roast#learningcontainer.com"
},
{
"userId": 4,
"firstName": "devid",
"lastName": "neo",
"phoneNumber": "222222222",
"emailAddress": "devid.neo#learningcontainer.com"
},
{
"userId": 5,
"firstName": "jone",
"lastName": "mac",
"phoneNumber": "111111111",
"emailAddress": "jone.mac#learningcontainer.com"
}
]
}
I should be able to split it in such a way that each userid goes to a different file.
So far, i have tried putting them to a map and try to split the map, and converting it into array and split the array with not much luck. The files contain the userid but it is not in json format anymore
Any suggestions on how this can be achieved in Java?
Expected result: {"users": [
{
"userId": 1,
"firstName": "Krish",
"lastName": "Lee",
"phoneNumber": "123456",
"emailAddress": "krish.lee#learningcontainer.com"
}
]
}

To process large files prefer to use stream/event oriented parsing. Both Gson and Jackson support that way. Just an illustration with a tiny JSON parser https://github.com/anatolygudkov/green-jelly:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Writer;
public class SplitMyJson {
private static final String jsonToSplit = "{\"users\": [\n" +
" {\n" +
" \"userId\": 1,\n" +
" \"firstName\": \"Krish\",\n" +
" \"lastName\": \"Lee\",\n" +
" \"phoneNumber\": \"123456\",\n" +
" \"emailAddress\": \"krish.lee#learningcontainer.com\"\n" +
" },\n" +
" {\n" +
" \"userId\": 2,\n" +
" \"firstName\": \"racks\",\n" +
" \"lastName\": \"jacson\",\n" +
" \"phoneNumber\": \"123456\",\n" +
" \"emailAddress\": \"racks.jacson#learningcontainer.com\"\n" +
" },\n" +
" {\n" +
" \"userId\": 3,\n" +
" \"firstName\": \"denial\",\n" +
" \"lastName\": \"roast\",\n" +
" \"phoneNumber\": \"33333333\",\n" +
" \"emailAddress\": \"denial.roast#learningcontainer.com\"\n" +
" },\n" +
" {\n" +
" \"userId\": 4,\n" +
" \"firstName\": \"devid\",\n" +
" \"lastName\": \"neo\",\n" +
" \"phoneNumber\": \"222222222\",\n" +
" \"emailAddress\": \"devid.neo#learningcontainer.com\"\n" +
" },\n" +
" {\n" +
" \"userId\": 5,\n" +
" \"firstName\": \"jone\",\n" +
" \"lastName\": \"mac\",\n" +
" \"phoneNumber\": \"111111111\",\n" +
" \"emailAddress\": \"jone.mac#learningcontainer.com\"\n" +
" }\n" +
" ]\n" +
"}";
public static void main(String[] args) {
final JsonParser parser = new JsonParser();
parser.setListener(new Splitter(new File("/home/gudkov/mytest")));
parser.parse(jsonToSplit); // if you read a file, call parse() several times part by part in a loop until EOF
parser.eoj(); // and then call .eoj()
}
static class Splitter extends JsonParserListenerAdaptor {
private final JsonGenerator jsonGenerator = new JsonGenerator();
private final AppendableWriter<Writer> appendableWriter = new AppendableWriter<>();
private final File outputFolder;
private int objectDepth;
private int userIndex;
Splitter(final File outputFolder) {
this.outputFolder = outputFolder;
if (!outputFolder.exists()) {
outputFolder.mkdirs();
}
jsonGenerator.setOutput(appendableWriter);
}
private boolean userJustStarted() {
return objectDepth == 2;
}
private boolean userJustEnded() {
return objectDepth == 1;
}
private boolean notInUser() {
return objectDepth < 2;
}
#Override
public boolean onObjectStarted() {
objectDepth++;
if (notInUser()) return true;
if (userJustStarted()) {
try {
appendableWriter.set(new FileWriter(new File(outputFolder, "user-" + userIndex + ".json")));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
userIndex++;
}
jsonGenerator.startObject();
return true;
}
#Override
public boolean onObjectEnded() {
if (notInUser()) {
objectDepth--;
return true;
}
objectDepth--;
jsonGenerator.endObject();
if (userJustEnded()) { // user object ended
try {
jsonGenerator.eoj();
appendableWriter.output().close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
return true;
}
#Override
public boolean onArrayStarted() {
if (notInUser()) return true;
jsonGenerator.startArray();
return true;
}
#Override
public boolean onArrayEnded() {
if (notInUser()) return true;
jsonGenerator.endArray();
return true;
}
#Override
public boolean onObjectMember(final CharSequence name) {
if (notInUser()) return true;
jsonGenerator.objectMember(name);
return true;
}
#Override
public boolean onStringValue(final CharSequence data) {
if (notInUser()) return true;
jsonGenerator.stringValue(data, true);
return true;
}
#Override
public boolean onNumberValue(final JsonNumber number) {
if (notInUser()) return true;
jsonGenerator.numberValue(number);
return true;
}
#Override
public boolean onTrueValue() {
if (notInUser()) return true;
jsonGenerator.trueValue();
return true;
}
#Override
public boolean onFalseValue() {
if (notInUser()) return true;
jsonGenerator.falseValue();
return true;
}
#Override
public boolean onNullValue() {
if (notInUser()) return true;
jsonGenerator.nullValue();
return true;
}
}
}
In this way you can easily implement filtering, aggregating etc. for really large files with the highest performance possible in regular Java.

Related

Grouping elements based on common element to form a json array of objects

im getting my data as whole json,but i expect it to be grouped based on a common element among the result itself
Data from query
firststring
secondstring
thirdstring
My Account
MyAccount
Menu1
My Cart
MyFavourites
Menu1
My Status
Status
Menu1
Orders
orders
Menu2
Damage Claim
DamageClaim
Menu2
my bean class
public class CommonThreeString implements Serializable{
private String firstString;
private String secondString;
private String thirdString;
public String getFirstString() {
return firstString;
}
public void setFirstString(String firstString) {
this.firstString = firstString;
}
public String getSecondString() {
return secondString;
}
public void setSecondString(String secondString) {
this.secondString = secondString;
}
public String getThirdString() {
return thirdString;
}
public void setThirdString(String thirdString) {
this.thirdString = thirdString;
}
}
My controller
#PostMapping("getMenuList")
public String getMenuList() throws ServiceException {
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = null;
try {
json = ow.writeValueAsString(iService.getMenuList());
} catch (JsonProcessingException e) {
}
return json;
}
service implementation
public List<CommonThreeString> getMenuList() throws ServiceException {
List<CommonTwoLongThreeString> menuList = null;
try {
menuList = Impl.getMenuListByPortalId(Long.valueOf("input"));
//query works done here//
} catch (ServiceException e) {
}
return menuList;
}
here im getting output as
[
{
"firstString": "My Account",
"secondString": "MyAccount",
"thirdString": "Menu1"
},
{
"firstString": "My Cart",
"secondString": "MyFavourites",
"thirdString": "Menu1"
},
{
"firstString": "My Status",
"secondString": "Status",
"thirdString": "Menu1"
},
{
"firstString": "orders",
"secondString": "orders",
"thirdString": "Menu2"
},
{
"firstString": "Damage Claim",
"secondString": "DamageClaim",
"thirdString": "Menu2"
}
]
The output im expecting
Menu1
[
{
"firstString": "My Account",
"secondString": "MyAccount",
--"thirdString": "Menu1"
},
{
"firstString": "My Cart",
"secondString": "MyFavourites",
--"thirdString": "Menu1"
},
{
"firstString": "My Status",
"secondString": "Status",
--"thirdString": "Menu1"
}
]
Menu2
[
{
"firstString": "orders",
"secondString": "orders",
--"thirdString": "Menu2"
},
{
"firstString": "Damage Claim",
"secondString": "DamageClaim",
--"thirdString": "Menu2"
}
]
the third String need to be the grouping factor
im want to group properly like the above thanks in advance
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.*;
public class TestJson {
public static void main(String[] args) {
String jsonString = null;
try {
jsonString = "[\n"
+ " {\n"
+ " \"firstString\": \"My Account\",\n"
+ " \"secondString\": \"MyAccount\",\n"
+ " \"thirdString\": \"Menu1\"\n"
+ " },\n"
+ " {\n"
+ " \"firstString\": \"My Cart\",\n"
+ " \"secondString\": \"MyFavourites\",\n"
+ " \"thirdString\": \"Menu1\"\n"
+ " },\n"
+ " {\n"
+ " \"firstString\": \"My Status\",\n"
+ " \"secondString\": \"Status\",\n"
+ " \"thirdString\": \"Menu1\"\n"
+ " },\n"
+ " {\n"
+ " \"firstString\": \"orders\",\n"
+ " \"secondString\": \"orders\",\n"
+ " \"thirdString\": \"Menu2\"\n"
+ " },\n"
+ " {\n"
+ " \"firstString\": \"Damage Claim\",\n"
+ " \"secondString\": \"DamageClaim\",\n"
+ " \"thirdString\": \"Menu2\"\n"
+ " }\n"
+ "]";
ObjectMapper mapper = new ObjectMapper();
com.google.gson.JsonArray dataArray = new JsonParser().parse(jsonString).getAsJsonArray();
HashMap<String, List<CommonThreeString>> groupByFieldMap = new HashMap<String, List<CommonThreeString>>();
for (JsonElement element : dataArray) {
String groupField = element.getAsJsonObject().get("thirdString").getAsString();
String firstStr = element.getAsJsonObject().get("firstString").getAsString();
String secondStr = element.getAsJsonObject().get("secondString").getAsString();
String thirdStr = element.getAsJsonObject().get("thirdString").getAsString();
if (groupByFieldMap.containsKey(groupField)) {
groupByFieldMap.get(groupField).add(new CommonThreeString(firstStr, secondStr, thirdStr));
} else {
ArrayList<CommonThreeString> emptyList = new ArrayList<CommonThreeString>();
emptyList.add(new CommonThreeString(firstStr, secondStr, thirdStr));
groupByFieldMap.put(groupField, emptyList);
}
}
StringWriter result = new StringWriter();
mapper.writeValue(result, groupByFieldMap);
System.out.println(result.toString());
} catch (Exception e) {
System.out.println("Exception "+e.getStackTrace());
}
}
}
Ref Here : how to do it
Grouping Json response with keys in java - android studio
Seems to be a duplicate ticket

Polymorphic deserialization of JSON with jackson with type info from parent node

I have this JSON documents
1:
{
"type": "first_type",
"configs": [
{
"itemLevel": 1,
"power": {
"firstTypeParam": "xxxx"
}
},
{
"itemLevel": 2,
"power": {
"firstTypeParam": "yyy"
}
}
]
}
2:
{
"type": "second_type",
"configs": [
{
"itemLevel": 11,
"power": {
"anotherParam": true
}
},
{
"itemLevel": 12,
"power": {
"anotherParam": false
}
]
}
A couple of java classes
public class Dto {
String type;
Collection<Config>;
}
public class Config {
int itemLevel;
Collection<Power> powers;
}
public interface Power {}
public class FirstPower implements Power {
String firstTypeParam;
}
public class SecondPower implements Power {
boolean anotherParam;
}
I tried to implement custom jackson deserializer #JsonDeserialize(using = MyStdDeserializer.class" on top of Power interface but couldn't find out how to access to neighbor node of the parent with type flag.
Do you know how to fix class hierarchy and/or use jackson features/annotations to deserialize JSON with "first_type" type onto FirstPower class and "second_type" onto SecondPower?
I'm using jackson 2.9.7
It is possible to change class hierarchy and JSON format little bit and also I have ability to use annotation-based deserialization.
Since the type information is stored in Dto class, the custom JsonDeserializer should be implemented for 'Dto' class instead of 'Power' interface in order to access the type information. The crucial part of the implementation of the custom JsonDeserializer in below code is the line
config.powers.add(parser.readValueAs(getPowerClass(dto.type)));
where getPowerClass method determine the class(FirstPower or SecondPower) required by using the type of dto. Once the class is known, we can deserialize the power object simply by calling readValueAs method. Following classes(should be put in same package) demonstrate how to implement the custom JsonDeserializer.
Main class
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class PolymorphicDeserialize {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
Dto type1 = mapper.readValue(getType1Json(), Dto.class);
Dto type2 = mapper.readValue(getType2Json(), Dto.class);
printDto(type1);
printDto(type2);
}
private static void printDto(Dto dto) {
System.out.println("type :" + dto.type);
for (Config config : dto.configs) {
System.out.println("itemLevel:" + config.itemLevel);
System.out.println("powers:" + config.powers);
}
}
private static String getType1Json() {
return " { "
+ " \"type\": \"first_type\", "
+ " \"configs\": [ "
+ " { "
+ " \"itemLevel\": 1, "
+ " \"power\": { "
+ " \"firstTypeParam\": \"xxxx\" "
+ " } "
+ " }, "
+ " { "
+ " \"itemLevel\": 2, "
+ " \"power\": { "
+ " \"firstTypeParam\": \"yyy\" "
+ " } "
+ " } "
+ " ] "
+ " } ";
}
private static String getType2Json() {
return " { "
+ " \"type\": \"second_type\", "
+ " \"configs\": [ "
+ " { "
+ " \"itemLevel\": 11, "
+ " \"power\": { "
+ " \"anotherParam\": true "
+ " } "
+ " }, "
+ " { "
+ " \"itemLevel\": 12, "
+ " \"power\": { "
+ " \"anotherParam\": false "
+ " } "
+ " } "
+ " ] "
+ " } ";
}
}
Dto class
import java.util.Collection;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
#JsonDeserialize(using = DtoDeserializer.class)
public class Dto {
String type;
Collection<Config> configs;
}
DtoDeserializer class
import java.io.IOException;
import java.util.ArrayList;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
public class DtoDeserializer extends JsonDeserializer<Dto> {
#Override
public Dto deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
Dto dto = new Dto();
dto.configs = new ArrayList<Config>();
while (parser.nextToken() == JsonToken.FIELD_NAME) {
deserializeType(parser, dto);
deserializeConfigs(parser, dto);
}
return dto;
}
private void deserializeType(JsonParser parser, Dto dto) throws IOException, JsonProcessingException {
if (!"type".equals(parser.getCurrentName())) {
return;
}
parser.nextToken();
dto.type = parser.getValueAsString();
}
private void deserializeConfigs(JsonParser parser, Dto dto) throws IOException, JsonProcessingException {
if (!"configs".equals(parser.getCurrentName())) {
return;
}
if (parser.nextToken() != JsonToken.START_ARRAY) {
return;
}
while (parser.nextValue() != null) {
if (parser.getCurrentToken() != JsonToken.START_OBJECT) {
continue;
}
Config config = new Config();
config.powers = new ArrayList<Power>();
while (parser.nextToken() != JsonToken.END_OBJECT) {
if ("itemLevel".equals(parser.getCurrentName())) {
parser.nextToken();
config.itemLevel = parser.getValueAsInt();
} else if ("power".equals(parser.getCurrentName())) {
parser.nextToken();
config.powers.add(parser.readValueAs(getPowerClass(dto.type)));
}
}
dto.configs.add(config);
}
}
private Class<? extends Power> getPowerClass(String type) {
if ("first_type".equals(type)) {
return FirstPower.class;
} else if ("second_type".equals(type)) {
return SecondPower.class;
}
throw new IllegalArgumentException("Not known type" + type);
}
}
Power interface
public interface Power {}
FirstPower class
public class FirstPower implements Power {
String firstTypeParam;
String getFirstTypeParam() {
return firstTypeParam;
}
void setFirstTypeParam(String firstTypeParam) {
this.firstTypeParam = firstTypeParam;
}
#Override
public String toString() {
return "firstTypeParam:" + firstTypeParam;
}
}
SecondPower class
public class SecondPower implements Power {
boolean anotherParam;
boolean isAnotherParam() {
return anotherParam;
}
void setAnotherParam(boolean anotherParam) {
this.anotherParam = anotherParam;
}
#Override
public String toString() {
return "anotherParam:" + String.valueOf(anotherParam);
}
}

How can I mapping Json to Model by Gson only needed fields

i have some Json string
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
How can I geg this model from this Json string by Gson
public class widget{
private String debug;
private String windowName; //name from widget->window->name
private String imageName; //name from widget->image->name
}
I do not wont create model with all fields and can I mapping needed for me fields from json to my model(even if they are chields)
I suggest you implement JsonDeserializer for each class you want to populate with data from JSON. E.g.:
package jsonsmartmap;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
public class WidgetMapper implements JsonDeserializer<WidgetMapper.Widget>
{
#Override
public Widget deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException
{
JsonObject json = (JsonObject) je;
JsonObject jsonWidget = json.get("widget").getAsJsonObject();
Widget ret = new Widget();
ret.setDebug(jsonWidget.get("debug").getAsString());
ret.setWindowName(jsonWidget.get("window").getAsJsonObject().get("name").getAsString());
ret.setImageName(jsonWidget.get("image").getAsJsonObject().get("name").getAsString());
return ret;
}
class Widget
{
private String debug;
private String windowName; //name from widget->window->name
private String imageName; //name from widget->image->name
public void setDebug(String debug)
{ this.debug = debug; }
public void setWindowName(String windowName)
{ this.windowName = windowName; }
public void setImageName(String imageName)
{ this.imageName = imageName; }
public String getDebug()
{ return this.debug; }
public String getWindowName()
{ return this.windowName; }
public String getImageName()
{ return this.imageName; }
#Override
public String toString()
{
return "Widget:"+getDebug()+","+getWindowName()+","+getImageName();
}
}
}
And the if you test it with provided json like this:
package jsonsmartmap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Main {
public static void main(String[] args) {
String inputJsonString = "{\"widget\": {\n" +
" \"debug\": \"on\",\n" +
" \"window\": {\n" +
" \"title\": \"Sample Konfabulator Widget\",\n" +
" \"name\": \"main_window\",\n" +
" \"width\": 500,\n" +
" \"height\": 500\n" +
" },\n" +
" \"image\": { \n" +
" \"src\": \"Images/Sun.png\",\n" +
" \"name\": \"sun1\",\n" +
" \"hOffset\": 250,\n" +
" \"vOffset\": 250,\n" +
" \"alignment\": \"center\"\n" +
" },\n" +
" \"text\": {\n" +
" \"data\": \"Click Here\",\n" +
" \"size\": 36,\n" +
" \"style\": \"bold\",\n" +
" \"name\": \"text1\",\n" +
" \"hOffset\": 250,\n" +
" \"vOffset\": 100,\n" +
" \"alignment\": \"center\",\n" +
" \"onMouseUp\": \"sun1.opacity = (sun1.opacity / 100) * 90;\"\n" +
" }\n" +
"}}";
Gson gson = (new GsonBuilder())
.registerTypeAdapter(WidgetMapper.Widget.class, new WidgetMapper())
.create();
WidgetMapper.Widget widget = gson.fromJson(inputJsonString, WidgetMapper.Widget.class);
System.out.println(widget.toString());
}
}
The output will be:
Widget:on,main_window,sun1
And this also provides good example of setter-getter solution for Gson.

Jackson get directly nested list as POJO

First of all the title might not be the best. Feel free to edit.
The problem: Assuming there is this json (quotation is missing, I know):
{
meta: {
code: 200
},
response: {
suggestedFilters: { },
suggestedRadius: 922,
headerLocation: "New York",
headerFullLocation: "New York",
headerLocationGranularity: "city",
totalResults: 246,
groups: [
{
type: "Recommended Places",
name: "recommended",
items: [
{
// item I care
},
{
// item I care
}
]
}
]
}
}
Is it necessary to pass the whole path in the POJO? For example now my class is:
#JsonIgnoreProperties(ignoreUnknown = true)
public class MyVenueResponse {
private VenueResponse response;
public VenueResponse getResponse() {
return response;
}
public class VenueResponse{
private List<VenueGroup> groups;
public List<VenueGroup> getGroups() {
return groups;
}
}
public class VenueGroup {
private ArrayList<GroupItems> items;
public ArrayList<GroupItems> getItems() {
return items;
}
}
}
I really do not care about all the medium classes but only about the public ArrayList<GroupItems> getItems(). Is there a way to "shortcut" the process and tell Jackson to skip the "response" and start from the groups object or doesn't know how to map it?
Note that I use databind like:
objectMapper.readValue(body.charStream(), MyVenueResponse.class); // where body is a ResponseBody from OKHttp
You can traverse the input JSON until the certain point using the Jackson Tree API and then convert a sub tree into a Java object. Here is an example:
public class JacksonNestedList {
public final static String JSON = "{\n"
+ " meta: {\n"
+ " code: 200\n"
+ " },\n"
+ " response: {\n"
+ " suggestedFilters: { },\n"
+ " suggestedRadius: 922,\n"
+ " headerLocation: \"New York\",\n"
+ " headerFullLocation: \"New York\",\n"
+ " headerLocationGranularity: \"city\",\n"
+ " totalResults: 246,\n"
+ " groups: [\n"
+ " {\n"
+ " type: \"Recommended Places\",\n"
+ " name: \"recommended\",\n"
+ " items: [\n"
+ " {\n"
+ " key: \"value1\"\n"
+ " },\n"
+ " {\n"
+ " key: \"value2\"\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ "}";
public static class GroupItem {
public String key;
#Override
public String toString() {
return "key:" + key;
}
}
public static void main(String[] args) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
final JsonParser items = mapper.readTree(JSON)
.path("response")
.path("groups")
.get(0)
.path("items")
.traverse();
System.out.println(mapper.readValue(items, new TypeReference<List<GroupItem>>() {}));
}
}
Output:
[key:value1, key:value2]

Trouble mapping JSON data to Java object

I'm having a little trouble working out an appropriate java object structure for the following JSON data:
"pages": {
"181382": {
"pageid": 181382,
"ns": 0,
"title": "Anonymity"
},
"7181837": {
"pageid": 7181837,
"ns": 0,
"title": "Anonymous"
}
}
The identifiers "181382" and "7181837" change depending on the data returned so these cannot be used as a member on an object. I tried to approach it using a Map<String, Object> approach but got a little stuck.
Edit:
This is what I've tried
public class PageData {
int pageid;
String ns;
String title;
public int getPageid() {
return pageid;
}
public String getNs() {
return ns;
}
public String getTitle() {
return title;
}
}
Map<String, PageData> pages = results.getPages().getData();
for (PageData data : pages.values()) {
System.out.println(data.getTitle());
}
Just create some wrapper for your Object. Here is working example:
Wrapper
public class Wrapper {
Map<String, PageData> pages = null;
public Map<String, PageData> getPages() {
return pages;
}
}
Launcher
public class Launcher {
public static void main(String[] args) {
String str = "{\"pages\": {\r\n" +
" \"181382\": {\r\n" +
" \"pageid\": 181382,\r\n" +
" \"ns\": 0,\r\n" +
" \"title\": \"Anonymity\"\r\n" +
" },\r\n" +
" \"7181837\": {\r\n" +
" \"pageid\": 7181837,\r\n" +
" \"ns\": 0,\r\n" +
" \"title\": \"Anonymous\"\r\n" +
" }\r\n" +
" }" +
"}";
Gson gson = new Gson();
Wrapper results = gson.fromJson(str, Wrapper.class);
Map<String, PageData> pages = results.getPages();
for (PageData data : pages.values()) {
System.out.println(data.getTitle());
}
}
}
PageData
public class PageData{/* the same */}
Output:
Anonymity
Anonymous

Categories