-
Notifications
You must be signed in to change notification settings - Fork 2.6k
JSON Pointer implementation #222
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
612e419
initial implementation of JSONPointer
erosb 5bee7e3
escape handling improvements & URL fragment notation handling
erosb 792c6f6
improved failure handling
erosb 45bd72c
added JSONObject#query() and JSONPointer#query() methods
erosb 5223aad
added some javadoc to JSONPointer
erosb bff3527
removed @author tag from JSONPointerException
erosb c1a789a
adding missing license headers
erosb cbb1546
README improvements for stleary/JSON-Java#218
erosb d833c2d
added builder class for JSONPointer, and implemented toString() and t…
erosb 5ae6a66
added javadoc & null check in Builder#append(String)
erosb c044eb1
added copying to JSONPointer constructor
erosb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,226 @@ | ||
| package org.json; | ||
|
|
||
| import static java.lang.String.format; | ||
| import static java.util.Collections.emptyList; | ||
|
|
||
| import java.io.UnsupportedEncodingException; | ||
| import java.net.URLDecoder; | ||
| import java.net.URLEncoder; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
|
|
||
| /* | ||
| Copyright (c) 2002 JSON.org | ||
|
|
||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
|
|
||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
|
|
||
| The Software shall be used for Good, not Evil. | ||
|
|
||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. | ||
| */ | ||
|
|
||
| /** | ||
| * A JSON Pointer is a simple query language defined for JSON documents by | ||
| * <a href="https://tools.ietf.org/html/rfc6901">RFC 6901</a>. | ||
| */ | ||
| public class JSONPointer { | ||
|
|
||
| private static final String ENCODING = "utf-8"; | ||
|
|
||
| public static class Builder { | ||
|
|
||
| private final List<String> refTokens = new ArrayList<String>(); | ||
|
|
||
| /** | ||
| * Creates a {@code JSONPointer} instance using the tokens previously set using the | ||
| * {@link #append(String)} method calls. | ||
| */ | ||
| public JSONPointer build() { | ||
| return new JSONPointer(refTokens); | ||
| } | ||
|
|
||
| /** | ||
| * Adds an arbitary token to the list of reference tokens. It can be any non-null value. | ||
| * | ||
| * Unlike in the case of JSON string or URI fragment representation of JSON pointers, the | ||
| * argument of this method MUST NOT be escaped. If you want to query the property called | ||
| * {@code "a~b"} then you should simply pass the {@code "a~b"} string as-is, there is no | ||
| * need to escape it as {@code "a~0b"}. | ||
| * | ||
| * @param token the new token to be appended to the list | ||
| * @return {@code this} | ||
| * @throws NullPointerException if {@code token} is null | ||
| */ | ||
| public Builder append(String token) { | ||
| if (token == null) { | ||
| throw new NullPointerException("token cannot be null"); | ||
| } | ||
| refTokens.add(token); | ||
| return this; | ||
| } | ||
|
|
||
| /** | ||
| * Adds an integer to the reference token list. Although not necessarily, mostly this token will | ||
| * denote an array index. | ||
| * | ||
| * @param arrayIndex the array index to be added to the token list | ||
| * @return {@code this} | ||
| */ | ||
| public Builder append(int arrayIndex) { | ||
| refTokens.add(String.valueOf(arrayIndex)); | ||
| return this; | ||
| } | ||
|
|
||
| } | ||
|
|
||
| /** | ||
| * Static factory method for {@link Builder}. Example usage: | ||
| * | ||
| * <pre><code> | ||
| * JSONPointer pointer = JSONPointer.builder() | ||
| * .append("obj") | ||
| * .append("other~key").append("another/key") | ||
| * .append("\"") | ||
| * .append(0) | ||
| * .build(); | ||
| * </code></pre> | ||
| * | ||
| * @return a builder instance which can be used to construct a {@code JSONPointer} instance by chained | ||
| * {@link Builder#append(String)} calls. | ||
| */ | ||
| public static Builder builder() { | ||
| return new Builder(); | ||
| } | ||
|
|
||
| private final List<String> refTokens; | ||
|
|
||
| /** | ||
| * Pre-parses and initializes a new {@code JSONPointer} instance. If you want to | ||
| * evaluate the same JSON Pointer on different JSON documents then it is recommended | ||
| * to keep the {@code JSONPointer} instances due to performance considerations. | ||
| * | ||
| * @param pointer the JSON String or URI Fragment representation of the JSON pointer. | ||
| * @throws IllegalArgumentException if {@code pointer} is not a valid JSON pointer | ||
| */ | ||
| public JSONPointer(String pointer) { | ||
| if (pointer == null) { | ||
| throw new NullPointerException("pointer cannot be null"); | ||
| } | ||
| if (pointer.isEmpty()) { | ||
| refTokens = emptyList(); | ||
| return; | ||
| } | ||
| if (pointer.startsWith("#/")) { | ||
| pointer = pointer.substring(2); | ||
| try { | ||
| pointer = URLDecoder.decode(pointer, ENCODING); | ||
| } catch (UnsupportedEncodingException e) { | ||
| throw new RuntimeException(e); | ||
| } | ||
| } else if (pointer.startsWith("/")) { | ||
| pointer = pointer.substring(1); | ||
| } else { | ||
| throw new IllegalArgumentException("a JSON pointer should start with '/' or '#/'"); | ||
| } | ||
| refTokens = new ArrayList<String>(); | ||
| for (String token : pointer.split("/")) { | ||
| refTokens.add(unescape(token)); | ||
| } | ||
| } | ||
|
|
||
| public JSONPointer(List<String> refTokens) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should either be a protected/private/or default constructor, and the List should be copied so the Pointer can't be modified outside of the class. this.refTokens = refTokens.clone();as it is now, I could do this: Builder b = JSONPointer.builder().append("key1");
JSONPointer jp1 = b.build();
b.append("key2");
JSONPointer jp2 = b.build();
if(jp1.toString().equals(jp2.toString()){
throw new Exception("Oops, my pointers are sharing a backing array");
} |
||
| this.refTokens = new ArrayList<String>(refTokens); | ||
| } | ||
|
|
||
| private String unescape(String token) { | ||
| return token.replace("~1", "/").replace("~0", "~") | ||
| .replace("\\\"", "\"") | ||
| .replace("\\\\", "\\"); | ||
| } | ||
|
|
||
| /** | ||
| * Evaluates this JSON Pointer on the given {@code document}. The {@code document} | ||
| * is usually a {@link JSONObject} or a {@link JSONArray} instance, but the empty | ||
| * JSON Pointer ({@code ""}) can be evaluated on any JSON values and in such case the | ||
| * returned value will be {@code document} itself. | ||
| * | ||
| * @param document the JSON document which should be the subject of querying. | ||
| * @return the result of the evaluation | ||
| * @throws JSONPointerException if an error occurs during evaluation | ||
| */ | ||
| public Object queryFrom(Object document) { | ||
| if (refTokens.isEmpty()) { | ||
| return document; | ||
| } | ||
| Object current = document; | ||
| for (String token : refTokens) { | ||
| if (current instanceof JSONObject) { | ||
| current = ((JSONObject) current).opt(unescape(token)); | ||
| } else if (current instanceof JSONArray) { | ||
| current = readByIndexToken(current, token); | ||
| } else { | ||
| throw new JSONPointerException(format( | ||
| "value [%s] is not an array or object therefore its key %s cannot be resolved", current, | ||
| token)); | ||
| } | ||
| } | ||
| return current; | ||
| } | ||
|
|
||
| private Object readByIndexToken(Object current, String indexToken) { | ||
| try { | ||
| int index = Integer.parseInt(indexToken); | ||
| JSONArray currentArr = (JSONArray) current; | ||
| if (index >= currentArr.length()) { | ||
| throw new JSONPointerException(format("index %d is out of bounds - the array has %d elements", index, | ||
| currentArr.length())); | ||
| } | ||
| return currentArr.get(index); | ||
| } catch (NumberFormatException e) { | ||
| throw new JSONPointerException(format("%s is not an array index", indexToken), e); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| StringBuilder rval = new StringBuilder(""); | ||
| for (String token: refTokens) { | ||
| rval.append('/').append(escape(token)); | ||
| } | ||
| return rval.toString(); | ||
| } | ||
|
|
||
| private String escape(String token) { | ||
| return token.replace("~", "~0") | ||
| .replace("/", "~1") | ||
| .replace("\\", "\\\\") | ||
| .replace("\"", "\\\""); | ||
| } | ||
|
|
||
| public String toURIFragment() { | ||
| try { | ||
| StringBuilder rval = new StringBuilder("#"); | ||
| for (String token : refTokens) { | ||
| rval.append('/').append(URLEncoder.encode(token, ENCODING)); | ||
| } | ||
| return rval.toString(); | ||
| } catch (UnsupportedEncodingException e) { | ||
| throw new RuntimeException(e); | ||
| } | ||
| } | ||
|
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| package org.json; | ||
|
|
||
| /* | ||
| Copyright (c) 2002 JSON.org | ||
|
|
||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
|
|
||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
|
|
||
| The Software shall be used for Good, not Evil. | ||
|
|
||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. | ||
| */ | ||
|
|
||
| /** | ||
| * The JSONPointerException is thrown by {@link JSONPointer} if an error occurs | ||
| * during evaluating a pointer. | ||
| */ | ||
| public class JSONPointerException extends JSONException { | ||
| private static final long serialVersionUID = 8872944667561856751L; | ||
|
|
||
| public JSONPointerException(String message) { | ||
| super(message); | ||
| } | ||
|
|
||
| public JSONPointerException(String message, Throwable cause) { | ||
| super(message, cause); | ||
| } | ||
|
|
||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
when we drop Java6 support, this can be changed to https://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html#UTF_8
java.nio.charset.StandardCharsets.UTF_8
maybe put in a comment noting that.