Skip to content

Commit

Permalink
Make JsonObject extend LinkedHashMap so that keys are ordered.
Browse files Browse the repository at this point in the history
  • Loading branch information
dweiss committed Dec 16, 2020
1 parent c31d402 commit c9523fa
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
12 changes: 6 additions & 6 deletions src/main/java/com/grack/nanojson/JsonObject.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@
*/
package com.grack.nanojson;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
* Extends a {@link HashMap} with helper methods to determine the underlying JSON type of the map element.
* Extends a {@link LinkedHashMap} with helper methods to determine the underlying JSON type of the map element.
*/
public class JsonObject extends HashMap<String, Object> {
public class JsonObject extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 1L;

/**
Expand Down Expand Up @@ -71,7 +71,7 @@ public JsonArray getArray(String key) {
public JsonArray getArray(String key, JsonArray default_) {
Object o = get(key);
if (o instanceof JsonArray)
return (JsonArray)get(key);
return (JsonArray) o;
return default_;
}

Expand Down Expand Up @@ -190,7 +190,7 @@ public JsonObject getObject(String key) {
public JsonObject getObject(String key, JsonObject default_) {
Object o = get(key);
if (o instanceof JsonObject)
return (JsonObject)get(key);
return (JsonObject) o;
return default_;
}

Expand All @@ -207,7 +207,7 @@ public String getString(String key) {
public String getString(String key, String default_) {
Object o = get(key);
if (o instanceof String)
return (String)get(key);
return (String) o;
return default_;
}

Expand Down
20 changes: 20 additions & 0 deletions src/test/java/com/grack/nanojson/JsonTypesTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertArrayEquals;

import java.math.BigInteger;
import java.util.Arrays;
Expand Down Expand Up @@ -184,4 +185,23 @@ public void testJsonArrayBuilderFailCantAddNonKeyToObject() {
JsonObject.builder().value(1);
}

@Test
public void testJsonKeyOrder() {
JsonObject a = JsonObject
.builder()
.value("key01", 1)
.value("key02", 2)
.value("key03", 3)
.value("key04", 4)
.done();

assertArrayEquals(
new String [] {
"key01",
"key02",
"key03",
"key04"
},
a.keySet().toArray(new String[0]));
}
}

0 comments on commit c9523fa

Please sign in to comment.