Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

What java class should I use for pair objects if I want to read them in from a json file with gson?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I see several options:

  1. You can use MutablePair instead of Pair. It should work out of the box.
  2. You might use Map<String,Object> instead of ArrayList<Pair<String, Object>>. This solution is valid only if parameter keys are unique.
  3. You can create your own Parameter class.
  4. If you insist on using Pair and you want to keep it immutable (actually it makes sense), you would need to implement your own TypeAdapter.
  5. Last but not least: use Jackson instead of Gson.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...