Line 156:
Line 156:
The <code>Codec.pair(codecA, codecB)</code> static method takes two codecs and generates a Codec<Pair<A,B>> from them.
The <code>Codec.pair(codecA, codecB)</code> static method takes two codecs and generates a Codec<Pair<A,B>> from them.
−
The only valid arguments for this method are codecs that serialize to objects, such as codecs created using [[Codecs#Records|RecordCodecBuilder]], [[Codecs#Maps|unboundedMap]], or fieldOf. Codecs that serialize nothing (such as [[Codecs#Unit|unit codecs]]) are also valid as they act as objects-with-no-fields.
+
The only valid arguments for this method are codecs that serialize to objects with explicit fields, such as codecs created using [[Codecs#Records|RecordCodecBuilder]] or [[Codecs#Boxing_values_as_objects|fieldOf]]. Codecs that serialize nothing (such as [[Codecs#Unit|unit codecs]]) are also valid as they act as objects-with-no-fields.
−
The resulting Pair codec will serialize a single object that has all of the fields of the two original codecs.
+
The resulting Pair codec will serialize a single object that has all of the fields of the two original codecs. For example:
+
<syntaxhighlight lang="java">
+
public static final Codec<Pair<Integer,String>> PAIR_CODEC = Codec.pair(
+
Codec.INT.fieldOf("value").codec(),
+
Codec.STRING.fieldOf("name").codec());
+
+
JsonElement encodedPair = BOXED_INT_CODEC.encodeStart(JsonOps.INSTANCE, Pair.of(5, "cheese").result().get();
+
</syntaxhighlight>
+
This codec serializes the above value to:
+
<syntaxhighlight lang="json">
+
{
+
"value": 5,
+
"name": "cheese"
+
}
+
</syntaxhighlight>
+
+
Codecs that serialize to objects with undefined fields such as [[Codecs#Maps|unboundedMap]] may cause strange and unpredictable behaviour when used here; these objects should be boxed via fieldOf when used in a pair codec.
==Either==
==Either==