ralfstx / minimal-json Goto Github PK
View Code? Open in Web Editor NEWA fast and small JSON parser and writer for Java
License: MIT License
A fast and small JSON parser and writer for Java
License: MIT License
Why have you choose to not use the standard class names with upper JSON
?
You could add JSONObject
and JSONArray
as empty subclasses, and have both?
I liked your library a lot, much simpler than most of the others. I found that a test here failed because the "id" property was in the end of the object instead of the beginning. According to json.org: "An object is an unordered set of name/value pairs".
Hi,
In the readme I see that it should be possible to iteratie over the elements of a JsonArray, but when I try that I get an error "Can't iterate over type: class com.eclipsesource.json.JsonArray".
I'm using JMeter 2.13 BeanShell Postprocessor and used the example from http://eclipsesource.com/blogs/2014/06/12/parsing-json-responses-with-jmeter/
The scripts looks like this:
import com.eclipsesource.json.*;
String jsonString = prev.getResponseDataAsString();
JsonObject family = JsonObject.readFrom(jsonString);
JsonArray members = family.get("members").asArray();
for (JsonValue member : members) {
// ...
}
The for-loops gives an error.
What am I doing wrong?
When setting values to floating point numbers which end on ".0" like this
jsonobject.set("test", (double) 21.0)
then the number is automatically truncated to an integer: {"test":21}
If I set a double value then I would expect the result to be a double and not an integer.
I had to remove this method in my project to be able to differ between integer/long and float/double.
Is this method essential in some way?
jackson is a big dependency (relatively to other components).
WriterConfig.PRETTY_PRINT
from https://github.com/ralfstx/minimal-json offers similar functionality for a tenth of the size.
Even for small numbers of elements, hash lookup is much faster than sequential search in a list.
This is not exactly an issue, but I need help accessing an array nested within a larger array in a JSON response.
Ralf,
I would like to know if you have intention to continue to support minimal json (last commit comes from 5 month)? Perhaps minimal json is now mature?
I post this question, because I'm using json-simple in https://github.com/angelozerr/tern.java and https://github.com/angelozerr/angularjs-eclipse and perhaps it could be more interesting to use minimal json (see angelozerr/tern.java#59)
Thank's for your reply
Regards Angelo
I think there should be a method which supports modifying the content of a value.
For example, when I have a array with 5 entries and I want to change the 3rd one. I have to make a 'temp' array where I add() entry 1 to 2 then add() a modified entry 3 and after that add the last 2 entries.
Now I have to remove() the array which I want to modify and add() the modidied Array.
This would be much easier when there is a replace() method because then I can directly modify entry number 3 and thats all.
Hope you understood what I mean :D
Perhaps it's my fault, but I have changes my pom with 0.9.3:
<dependency>
<groupId>com.eclipsesource.minimal-json</groupId>
<artifactId>minimal-json</artifactId>
<version>0.9.3</version>
</dependency
, and I have the following errors :
[ERROR] Failed to execute goal on project _a: Could not resolve dependencies for project __a:_a:jar:0.0.1-SNAPSHOT:
Failed to collect dependencies at com.eclipsesource.minimal-json:minimal-json:jar:0.9.3: Failed to read artifact descriptor for com.eclipsesource.minimal-json:minimal-json:jar:0.9.3:
Could not find artifact com.eclipsesource.minimal-json:parent:pom:0.9.3 in central (http://repo.maven.apache.org/maven2) -> [Help 1]
Any help are welcome, thanks!
Example:
JsonArray array = new JsonArray().add( 23 ).add( true );
Is it possible to add minimal-json 0.9.2 in maven central?
JsonObject.readFrom(String)
's javadoc says that it throws an UnsupportedOperationException
but it actually throws a com.eclipsesource.json.ParseException
In JsonObject
either the javadoc or the code is wrong.
the method's javadoc readFrom(String)
says
* @throws UnsupportedOperationException
* if the input does not contain a JSON object
However, if the input doesn't contain a JSON object it throws a com.eclipsesource.json.ParseException
instead.
Seems like the javadoc and the actual exception being thrown don't match in other places.
Probably related to #8
Running this unit test
package com.eclipsesource.json;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class JsonObjectReadFromTest {
@Test(expected = java.lang.UnsupportedOperationException.class)
public void JsonObjectReadFrom() {
JsonObject jsonObject = JsonObject
.readFrom("This is not a JSON object");
}
@Test
public void parseExceptionIsUnsupportedOperationException() {
Exception pex = new ParseException("", 0, 0, 0);
assertTrue("ParseException is not an UnsupportedOperationException ",
pex instanceof UnsupportedOperationException);
}
}
The result is
java.lang.Exception: Unexpected exception, expected<java.lang.UnsupportedOperationException> but was<com.eclipsesource.json.ParseException>
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
....
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:19)
... 15 more
Is there a user mailing list/forum for minimal-json?
How can I install minimal-json library using Gradle?
Thank
is it intentional that an exception is thrown if the json data uses single quotes ' rather than double quotes " ? can support for this be added, or is there a reason it's not?
Hi,
Thanks for the great library.
Is it possible to support merging for the JsonObject.
json-smart has similar feature: https://code.google.com/p/json-smart/wiki/MergeSample
When asXxx methods are used internally, e.g. in static factory methods, a UOE is not appropriate.
To be more precise, this class is used for literals, not for primitive types.
It would be good to have a changelog available, so users can see if upgrading makes sense to them - and what the latest stable release is...
Currently minimal-json
allows duplicated names, which is contrary to section 4 of RFC7159, which says: The names within an object SHOULD be unique.
Other parsers throw an exception. JSON in Java for example throws
org.json.JSONException: Duplicate key "status" at
....
@ralfstx I'm developping a JSON Editor based on WTP https://github.com/angelozerr/eclipse-wtp-json (I will contribute to WTP soon).
I'm supporting JSON Schema for :
by using JSON Schema at http://schemastore.org/
I have developed my own JSON Schema (works only for completion) because every JSON Schema written in Java doesn't support line number where there is an error. It's because the JSON source to validate doesn't contains line number, offset for each JsonValue.
I create this issue because I would liek to know if minimal-json could :
If you are not aware to do that, close this issue and I will create my own minimal-json with those extension.
Ideally, these factory methods should support varargs. Not sure about the method name.
JsonArray.createArray( 1, 2, 3 );
Or should the methods go to JsonValue to be next to valueOf( ... )?
JsonValue.createArray( "a", "b", "c" );
Or on a Util class like so:
Json.createJsonArray( 1, 2, 3 );
Is this available on the online maven repository? I cannot find it.
Like J2V8, it should be cool if SNAPSHOT minimal-json could be available at https://oss.sonatype.org/content/repositories/snapshots/com/eclipsesource/
I'm trying to run the benchmark. The performancetest subproject's README.md says: "To run a benchmark, use the benchmark's main method."
It took me a while before I realized I needed to run the command to copy all the JARs into "lib" and then launch things manually:
# java -cp target/classes:$(ls lib/*.jar | tr ' ' ':') com.eclipsesource.json.performancetest.ReadWriteBenchmark
Two ways to make life easier:
mvn exec:java doesn't work
# mvn exec:java -Dexec.mainClass="com.eclipsesource.json.performancetest.ReadWriteBenchmark"
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building minimal-json performance tests 0.9.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- exec-maven-plugin:1.3.2:java (default-cli) @ minimal-json-performancetest ---
[WARNING] Warning: killAfter is now deprecated. Do you need it ? Please comment on MEXEC-6.
0% Scenario{vm=java, trial=0, benchmark=ReadFromString, input=rap, parser=org-json} Failed to execute java -cp /usr/local/Cellar/maven/3.2.3/libexec/boot/plexus-classworlds-2.5.1.jar com.google.caliper.InProcessRunner --warmupMillis 3000 --runMillis 1000 --measurementType TIME --marker //ZxJ/ -Dbenchmark=ReadFromString -Dinput=rap -Dparser=org-json com.eclipsesource.json.performancetest.ReadWriteBenchmark
Error: Could not find or load main class com.google.caliper.InProcessRunner
An exception was thrown from the benchmark code.
com.google.caliper.ConfigurationException: Failed to execute java -cp /usr/local/Cellar/maven/3.2.3/libexec/boot/plexus-classworlds-2.5.1.jar com.google.caliper.InProcessRunner --warmupMillis 3000 --runMillis 1000 --measurementType TIME --marker //ZxJ/ -Dbenchmark=ReadFromString -Dinput=rap -Dparser=org-json com.eclipsesource.json.performancetest.ReadWriteBenchmark
at com.google.caliper.Runner.measure(Runner.java:309)
at com.google.caliper.Runner.runScenario(Runner.java:229)
at com.google.caliper.Runner.runOutOfProcess(Runner.java:378)
at com.google.caliper.Runner.run(Runner.java:97)
at com.eclipsesource.json.performancetest.caliper.CaliperRunner.safeRun(CaliperRunner.java:114)
at com.eclipsesource.json.performancetest.caliper.CaliperRunner.exec(CaliperRunner.java:57)
at com.eclipsesource.json.performancetest.ReadWriteBenchmark.main(ReadWriteBenchmark.java:131)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:293)
at java.lang.Thread.run(Thread.java:745)
Is Caliper trying to do runtime class loading?
Building classpath without copying
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<configuration>
<outputFile>${project.build.directory}/runtime-classpath</outputFile>
<includeScope>runtime</includeScope>
</configuration>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>build-classpath</goal>
</goals>
</execution>
</executions>
</plugin>
This way, a helper shell script can just do "-cp $(cat target/runtime-classpath)", eliminating the JAR copying step.
right now, the conversion seems to be just only one-way, i.e. JSON string to custom Java object (JsonValue, JsonObject, ...)
Why are methods like isInteger()
missing? Are simplicity and minimalism the reasons?
Right now there is only isNumber()
so I use
jsonvalue.toString().contains(".")
additionally as a workaround to check whether the number is an "integer" or not.
Hi,
I was looking for a way to parse both json object or array and test afterward which one it is. I found a way but I think it should be added to the readme doc. Here is what I did:
try{
JsonValue value = JsonValue.readFrom(jsonString);
if (value instanceof JsonObject) {
object = (JsonObject) value;
} else {
array = (JsonArray) value;
}
}catch(RuntimeException e){
// process error
}
Hi there.
With version 0.9.3 which is available in maven central:
http://search.maven.org/#artifactdetails|com.eclipsesource.minimal-json|minimal-json|0.9.3|bundle
it seems there was a maven parent pom introduced.
But this parent pom is not available in Maven central, so when using minimal-json 0.9.3 my build fails with:
Failed to collect dependencies at com.eclipsesource.minimal-json:minimal-json:jar:0.9.3: Failed to read artifact descriptor for com.eclipsesource.minimal-json:minimal-json:jar:0.9.3: Could not find artifact com.eclipsesource.minimal-json:parent:pom:0.9.3
For example, ParseException does not need a public constructor.
JsonObject does not prevent duplicate names, because RFC 4627 does not. For example, it is possible to create a JsonObject for { "a": 1, "a": 2 }
.
In case of duplicate names in an object, the behavior of the methods get() and remove() should be revised. The current behavior is that get( name )
returns the value of the first matching member, and also remove( name )
deletes only the first one.
It seems more intuitive that a member “shadows” previous members with the same name. Following this logic, get( name ) should always return the last member with this name. This would also ensure that calling get( name )
directly after add( name, value )
will always return value
.
For remove( name ) there seem to be different options:
remove( name )
directly after add( name, value )
would revert the addition and leave the object in the previous state.get( name )
directly after remove( name )
will always return null
regardless of the previous state.Hi.
We found out that when parsing a very (very very) deeply nested JSON Object (~ 4.000 levels) with Json.parse(String)
minimaljson runs out of "Stack" with a java.lang.StackOverflowError
(which is quite understandable) :)
Of course this is no "use case" for us - it just came up during a pentest which then caused a JVM crash.
Would it be possible to add a configuration to the JsonParser
which configures a maximum nesting level?
And then throwing a ParseException
when parsing a too deeply nested JSON-String.
I am new to github and not sure if I am in correct place here??
I am developing a web project and I am using TeaVM an ahead-of-time translating compiler (transpiler) from Java bytecode to JavaScript , and it has some restriction of some parts of JDK can used in TeaVM for example java.lang.reflect not fully supported
and among not supported classes is java.io.StringWriter witch used by minimal-json so is it possible to get a version of minimal-json can run under this environment .thanks
Making JsonNumber
public would allow to create JSON numbers that does not fit into any of the primitive Java types. Examples would be numbers with arbitrary precision, e.g. BigInteger and BigDecimal. Alternatively, factory methods could be offered for these two types.
With the constants NULL
, TRUE
, and FALSE
defined on JsonValue
, these constants are inherited by the subtypes of JsonValue
. For example, the expression JsonArray.TRUE
would compile although it doesn't make any sense. The same is true for static factory methods. The expression JsonArray.valueOf(true)
would also compile and return JsonValue.TRUE
which is not an instance of JsonArray
.
Moving these constants and factory methods to a dedicated class Json
would solve these issues. Moreover, it would result in shorter and more concise code:
Json.NULL
, Json.TRUE
, etc. instead of JsonValue.NULL
, JsonValue.TRUE
.
We could consider to rename the factory methods to value
instead of valueOf
.
Json.value(true)
, Json.value(23)
...
This would also allow to add factory methods for arrays such as:
Json.array(23, 42)
, etc.
The following code
JsonObject object = JsonObject.readFrom( "{ \"globals\": 23, \"undef\": true }" );
object.remove( "globals" );
object.get( "indent" );
leads to
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.RangeCheck(ArrayList.java:546)
at java.util.ArrayList.get(ArrayList.java:321)
at com.eclipsesource.json.JsonObject.indexOf(JsonObject.java:617)
at com.eclipsesource.json.JsonObject.get(JsonObject.java:516)
...
Json.array() should return JsonArray and it returns JsonValue.
I think that this is an issue.
this example:
JsonArray user = Json.array().add("Bob").add(42);
// -> ["Bob", 42]
don't work without casting
Thanks,
It should be cool if we could customize the JsonWriter to indent JSON.
An indent option could be added in the JsonValue#writeTo(Writer writer, Integer indent) to indent the JSON stream.
It should be possible to
I just wanted to thank you for minimal-json. I used it as a base for a Hjson implementation.
Having to supply a default value on the JsonObject.getXXX methods is sometimes a bit tedious. Often times you just want the string to be null or the boolean to be false. So there should be a variant where it is not required to provide a default value.
Is it possible to find the line of a JsonValue in a file? I'd like to throw an exception relating to an invalid field value and it would be nice if I could provide the line of the issue, also meaning I can retrieve the actual text itself to include in the exception.
It would be useful for generating exceptions like this:
Failed to parse JSON!
"myValue" can't be null on line 7:
...
"myValue": null,
...
When parsing {"abc":null}
jsonObject.getLong("abc",0);
throws a NumberFormatException because the value is somehow converted to "null"
Unsure if we're supposed to use jsonObject.get().isNull() or if we could enhance the method below to do the null checking instead.
public JsonValue get(String name) {
if(name == null) {
throw new NullPointerException("name is null");
} else {
int index = this.indexOf(name);
// if NullLiteral.equals(this.values.get(index)) ??
return index != -1?(JsonValue)this.values.get(index):null;
}
}
minimal-json is available on maven central repository, but is it available too on P2 repository?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.