Skip to content

Commit 991994f

Browse files
ehughsbairdRenechCDDA
authored andcommitted
Generic reader for vector of pairs
1 parent 35c8340 commit 991994f

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/generic_factory.h

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2010,6 +2010,43 @@ class pair_reader : public generic_typed_reader<pair_reader<T>>
20102010
}
20112011
};
20122012

2013+
// Reads into a vector of pairs in the format (example)
2014+
// "growth_stages": [ { "GROWTH_SEED": "23 days" }, { "GROWTH_SEEDLING": "23 days" }, { "GROWTH_MATURE": "23 days" }, { "GROWTH_HARVEST": "22 days" } ]
2015+
// OR
2016+
// "growth_stages": [ [ "GROWTH_SEED", "23 days" ], [ "GROWTH_SEEDLING", "23 days" ], [ "GROWTH_MATURE", "23 days" ], [ "GROWTH_HARVEST", "22 days" ] ]
2017+
// The key(K) of the pair object must be string constructable.
2018+
template<typename K, typename V>
2019+
class vector_pair_reader : public generic_typed_reader<vector_pair_reader<K, V>>
2020+
{
2021+
public:
2022+
std::pair<K, V> get_next( const JsonValue &jv ) const {
2023+
if( jv.test_object() ) {
2024+
JsonObject jo = jv.get_object();
2025+
if( jo.size() != 1 ) {
2026+
jv.throw_error( string_format( "Expected size of 1 for JsonObject, found size %d", jo.size() ) );
2027+
}
2028+
for( JsonMember jm : jo ) {
2029+
K key( jm.name() );
2030+
V ret;
2031+
jm.read( ret );
2032+
return std::make_pair( key, ret );
2033+
}
2034+
}
2035+
if( !jv.test_array() ) {
2036+
jv.throw_error( "bad pair" );
2037+
}
2038+
JsonArray ja = jv.get_array();
2039+
if( ja.size() != 2 ) {
2040+
ja.throw_error( "Must have 2 elements" );
2041+
}
2042+
K l;
2043+
V h;
2044+
ja[0].read( l, true );
2045+
ja[1].read( h, true );
2046+
return std::make_pair( l, h );
2047+
}
2048+
};
2049+
20132050
template<typename T1, typename T2>
20142051
class named_pair_reader : public generic_typed_reader<named_pair_reader<T1, T2>>
20152052
{

0 commit comments

Comments
 (0)