I am writing json files with gson (in Java), but I also want to read them back in. And, I have some data representing key,value pairs (where the key is only known at runtime), so I want to use a pair class to represent them, I am currently using the pair class from org.apache.commons.lang3.tuple, but it doesn't have a noArg constructor like gson needs to read the data back in, and thus the code fails when I do that step. Is there some other class that would work better? Here is a small version of the code I want.
import org.apache.commons.lang3.tuple.Pair;
import com.google.gson.GsonBuilder;
import com.google.gson.GsonBuilder;
class JsonFile { ArrayList<Event> events;
Public void diff(JsonFile other) {
// code not shown, but checks some things for being equal
}
}
class Event { String type; // of event
Parameters params;
Public Event(String type, Parameters params) {
this.type = type;
this.params = params;
}
}
class Parameters extends ArrayList<Pair<String, Object>> {}
JsonFile eventsToWrite; // populated by code
JsonFile eventstoDiff; // a stored copy of what the file "should" look like
// ...
// Some code filling eventsToWrite
Parameters params = new Parameters();
params.add(Pair.of("xyzzy", "is a magic name"));
params.add(Pair.of("foo", "bar");
Event event = new Event("lispy event", params);
eventsToWrite.add(event);
// ...
Reader reader new BufferedReader(new FileReader(new File("toDiff.json")));
GsonBuilder bld = new GsonBuilder();
Gson gsonRead = bld.create();
eventsToDiff = gsonRead.fromJson(reader, JsonFile.class); // this fails
eventsToWrite.diff(eventsToDiff);
question from:
https://stackoverflow.com/questions/65940543/what-java-class-should-i-use-for-pair-objects-if-i-want-to-read-them-in-from-a-j 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…