Code Monkey home page Code Monkey logo

json-lib's Introduction

Json-lib

Build Status Download


json lib

JSON-lib is a java library for transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans.

Refer to the project guide for further information on configuration and usage.

Enterprise Support

Available as part of the Tidelift Subscription.

The maintainers of org.kordamp.json:json-lib-core and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. Learn more.

json-lib's People

Contributors

aalmiray avatar alanscut avatar github-actions[bot] avatar hertzsprung avatar jglick avatar kohsuke avatar kunsingh avatar mniedero avatar ollin avatar paulk-asert avatar rac2030 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

json-lib's Issues

Problem with licensing

Your library says that it includes code written by Douglas Crockford. That seems very likely to be the json.org json library.

That library had a license that is not Apache License compatible. Inclusion of that code would make your library incompatible with the Apache License.

I have a few questions and a suggestion:

  1. is that the code you are referring to in your POM?

  2. if so, can you clarify your license so that people don't misunderstand and think that your code is open source.

  3. is it possible to switch your dependency to a library that has a valid open source license? I would offer https://github.com/tdunning/open-json as an example of such.

Issue with String escaping in JSONObject

Code:

JSONObject json = new JSONObject();
json.put("key1", "[...]");
json.put("key2", "[title]");
System.out.println(json.toString());

Output:

{"key1":["..."],"key2":"[title]"}

Many of our String data values are enclosed in square brackets. For key1, the data is [...] but the String value is converted into an array while converting to JSON. For key2, it is correctly serialized as a String.

Is there any way to prevent this by escaping the data or using some settings ?

Thanks.

JSON to XML and back

Hi,

I need to parse JSON to XML and back again. I didn't expected that the JSON input and the JSON output (after two parsing steps) differ form each other. The alphabetical ordering isn't an issue. The problem is, that the generated "e" from the XML appears in JSON. On one hand it is plausible, that the XML is parsed strictly to JSON without modification. On the other hand it's just irritating that the JSON changes after parsing back and forth. What is your advise for this problem? Is there already a feature implemented? Or do i need to write a parser by myself?

Thanks in advance,
Sebastian

Would Json-lib keep in maintaining?

Hi Andres @aalmiray , json-lib has been widely used in the past few years, although there are a lot of excellent JSON parse software available for developers to choose from, there are still many people who will continue to choose json-lib. In order to make json-lib users have better support, would you consider adding a collaborator to help you manage the community, handle some issues, fix bugs, even add some new features?

Update xercesImpl

Sonatype Lift reports:

[CVE-2012-0881] Apache Xerces2 Java Parser before 2.12.0 allows remote attackers to cause a denial of service (CPU consumption) via a crafted message to an XML service, which triggers hash table collisions.
[CVE-2013-4002] CWE-400: Uncontrolled Resource Consumption ('Resource Exhaustion')
[CVE-2022-23437] CWE-91: XML Injection (aka Blind XPath Injection)
[sonatype-2017-0348] CWE-833: Deadlock
[CVE-2009-2625] CWE-400: Uncontrolled Resource Consumption ('Resource Exhaustion')

Access to default bean proccesing

Hi, when i try to register bean/value proccesor usually i need to rely on default proccesing to modify the default json on the fly, while keeping the rest of configuration.
The problem is the default proccesing is not accesible from the custom proccesors (is in the private method JSONObject.defaultBeanProcessing)
To avoid circular calls i have to unregister proccesor/call fromObject with provided config/reregister proccesor, in the proccesor itself!
Maybe there is another more elegant way to get it
Thanks and congrats for the lib

Can't download the new release json-lib through maven or gradle

Hi Andres @aalmiray , the introduction of the latest json-lib in readme is as follows:
in gradle:

dependencies {
    compile 'org.kordamp.json:json-lib:3.0.1'  // should change to:  json-lib-core
}

in maven:

<dependency>
    <groupId>org.kordamp.json</groupId>
    <artifactId>json-lib</artifactId>  // also should change to: json-lib-core
    <version>3.0.1</version>
</dependency>

Actually, the real name of the json-lib jar file you uploaded to maven2 repo is json-lib-core : http://repo.maven.apache.org/maven2/org/kordamp/json/json-lib-core/3.0.1/
Only by changing the artifactId to json-lib-core can we download the jar file successfully. Or change the name of jar file to json-lib.

XML element ordering

Hello,
is it possible to make the alphabetical XML element ordering optional?

(referres to XMLSerializer.java line 942: Arrays.sort( names );)
thanks

Floats/Doubles are outputted as Integers

Can you make a configuration option at least to output double/float values with the trailing zeros intact? It looks like doubles are trimmed from 1.0 to 1, removing the trailing period and zeros. I would like to keep this intact for our API.

error occurs when i run "maven install" ,becase of the version of plugin

error as follows:
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:145)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:195)
... 19 more

Caused by: org.apache.maven.plugin.PluginContainerException: An API incompatibility was encountered while executing org.codehaus.groovy.maven:gmaven-plugin:1.0-rc-3:compile: java.lang.NoSuchMethodError: org.codehaus.plexus.PlexusContainer.hasChildContainer(Ljava/lang/String;)Z

realm = plugin>org.codehaus.groovy.maven:gmaven-plugin:1.0-rc-3

when changing the version of gmaven-plugin to 1.0-rc-5 , it's OK

json-lib2.4 method _fromJSONObject of JSONObject class bug

I find method _fromJSONObject of JSONObject class has a bug,
jsonObject.setInternal( key, value, jsonConfig );
should be jsonObject._setInternal( key, value, jsonConfig );

run the following code is error.
Tried to assign property id:java.lang.String to bean of class java.lang.String
Exception in thread "main" net.sf.json.JSONException: java.lang.IllegalArgumentException: Cannot invoke com.eheres.test.Tb.setPortalLayout on bean class 'class com.eheres.test.Tb' - argument type mismatch - had objects of type "[Ljava.lang.String;" but expected signature "java.lang.String"

code:

public class Tb {
    private String columns;
    private String portalLayout;
    public String getColumns() {
            return columns;
    }
    public void setColumns(String columns) {
            this.columns = columns;
    }
    public String getPortalLayout() {
            return portalLayout;
    }
    public void setPortalLayout(String portalLayout) {
            this.portalLayout = portalLayout;
    }
}

public class Rs {
    private List<Tb> records;
    public List<Tb> getRecords() {
        return records;
    }
    public void setRecords(List<Tb> records) {
        this.records = records;
    }   
}

public static void main(String[] args) {
    Tb t = new Tb();
    t.setColumns("2");
    t.setPortalLayout("[{\"id\":\"UserOrgs\"}]");

    List<Tb> ts = new ArrayList<Tb>();
    ts.add(t);
    Rs rs = new Rs();
    rs.setRecords(ts);

    JSONObject objr = JSONObject.fromObject(rs);

    String jsonr = objr.toString();
    System.out.println(jsonr);

    JSONObject objr2= JSONObject.fromObject(jsonr);
    Map map = new HashMap();
    map.put("records",Tb.class);
    Rs rs2 = (Rs)JSONObject.toBean(objr2, Rs.class,map);

    Tb tr2 = rs2.getRecords().get(0);
    System.out.println(tr2.getPortalLayout());
}

JSONNull is a singleton class implements Serializable, but don't have "readResolve" method

JSONNull is a singleton class implements Serializable, but don't have "readResolve" method.
So when serialize JSONNull object in Memcache, and deserializes it, it create a new JSONNull object instance, JSONUtil.isNull() can't judge this correctly.

About "readResolve" method, refer to: http://docs.oracle.com/javase/7/docs/platform/serialization/spec/input.html#5903
About singleton class implements Serializable, refer to:
http://stackoverflow.com/questions/3930181/how-to-deal-with-singleton-along-with-serialization

java heap space: OOM

hi Andres, some particular scenario will trigger the OOM Exception in JSONObject.fromObject():

String str = "{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}:1}";
JSONObject object = JSONObject.fromObject(str);
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at java.base/java.util.Arrays.copyOf(Arrays.java:3746)
	at java.base/java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:172)
	at java.base/java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:748)
	at java.base/java.lang.StringBuffer.append(StringBuffer.java:424)
	at org.kordamp.json.JSONObject.toString(JSONObject.java:2079)
        ...

The problem lies in the buffer allocation memory:
JSONUitls.java

   public static String quote(String string) {
       ...
       StringBuffer sb = new StringBuffer(len * 2);
       ...

Since double quotes need to be escaped, the number of slash symbol will grow exponentially with the number of nested layers.

Missing license information for the json.org code

Hi,

The <license> section of pom.xml mentions that "This product includes software developed by Douglas Crockford (http://www.crockford.com).", but the license applicable to this code isn't specified. For clarity if JSON-lib was derived from the original json.org library I think the LICENSE.txt file should mention it and include the json.org license after the Apache-2.0 license:

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.

Xml to Json array

When converting XML to Json, if an element has only one child it won't be interpreted as a collection and it can cause problems:

i.e.

<foo>
  <bar>1</bar>
  <bar>1</bar>
  <bar>1</bar>
</foo>

will be converted to:


{ foo: [ {bar: 1}, {bar: 1}, {bar: 1} ] }

But,

<foo>
  <bar>1</bar>
</foo>

will be converted to:


{ foo: {bar: 1} }

So is there a way to tell XMLSerializer that an element should be an array?

Annotation support in JSON lib?

I am trying to convert a JSON Object to JAVA Bean using JSON lib.

The JSON format is:

{
"services": [
{
"url": "https://stashboardni.appspot.com/api/v1/services/fpga-compile-cloud…",
"id": "fpga-compile-cloud-beta",
"description": "FPGA Compile Cloud Beta",
"name": "FPGA Compile Cloud Beta",
"current-event": {
"status": {
"description": "The service is up",
"level": "NORMAL",
"url": "https://stashboardni.appspot.com/api/v1/statuses/up",
"image": "https://stashboardni.appspot.com/images/status/tick-circle.png",
"id": "up",
"name": "up"
},
"url": "https://stashboardni.appspot.com/api/v1/services/fpga-compile-cloud…",
"timestamp": "Mon, 14 Feb 2011 22:35:38 GMT",
"sid": "agxzdGFzaGJvYXJkbmlyDQsSBUV2ZW50GIH6AQw",
"message": "Service is working properly.",
"informational": false
}
},
{
"url": "https://stashboardni.appspot.com/api/v1/services/labview-web-ui-bui…",
"id": "labview-web-ui-builder",
"description": "LabVIEW Web UI Builder",
"name": "LabVIEW Web UI Builder",
"current-event": {
"status": {
"description": "The service is up",
"level": "NORMAL",
"url": "https://stashboardni.appspot.com/api/v1/statuses/up",
"image": "https://stashboardni.appspot.com/images/status/tick-circle.png",
"id": "up",
"name": "up"
},
"url": "https://stashboardni.appspot.com/api/v1/services/labview-web-ui-bui…",
"timestamp": "Thu, 17 Feb 2011 15:50:50 GMT",
"sid": "agxzdGFzaGJvYXJkbmlyDQsSBUV2ZW50GNKJAgw",
"message": "Service is working properly",
"informational": false
}
},
{
"url": "https://stashboardni.appspot.com/api/v1/services/ni-hosted-services…",
"id": "ni-hosted-services-emails",
"description": "The system that handles sending emails for password resets, new acc…",
"name": "NI Hosted Services Emails",
"current-event": {
"status": {
"description": "The service is up",
"level": "NORMAL",
"url": "https://stashboardni.appspot.com/api/v1/statuses/up",
"image": "https://stashboardni.appspot.com/images/status/tick-circle.png",
"id": "up",
"name": "up"
},
"url": "https://stashboardni.appspot.com/api/v1/services/ni-hosted-services…",
"timestamp": "Mon, 14 Feb 2011 22:36:03 GMT",
"sid": "agxzdGFzaGJvYXJkbmlyDQsSBUV2ZW50GJXLAQw",
"message": "Service is working properly.",
"informational": false
}
},
{
"url": "https://stashboardni.appspot.com/api/v1/services/ni-hosted-services…",
"id": "ni-hosted-services-login",
"description": "NI Hosted Services Login",
"name": "NI Hosted Services Login",
"current-event": {
"status": {
"description": "The service is up",
"level": "NORMAL",
"url": "https://stashboardni.appspot.com/api/v1/statuses/up",
"image": "https://stashboardni.appspot.com/images/status/tick-circle.png",
"id": "up",
"name": "up"
},
"url": "https://stashboardni.appspot.com/api/v1/services/ni-hosted-services…",
"timestamp": "Mon, 14 Feb 2011 22:36:55 GMT",
"sid": "agxzdGFzaGJvYXJkbmlyDQsSBUV2ZW50GJbLAQw",
"message": "Service is working properly. ",
"informational": false
}
}
]
}

My Java code which serializes this JSON to Java Bean is:

jsonResp = JSONObject.fromObject(strResponse);
if (jsonResp != null) {
sList = MorphToJavaBean(jsonResp);
}

private StashBoardServices MorphToJavaBean(JSONObject prmJSONObject) {
if (prmJSONObject == null) {
return null;
}

    StashBoardServices sServices = null;
    Map classMap = null;
    MorpherRegistry morpherRegistry = null;
    Morpher dynaMorpher = null;
    List services = null;
    try {
        JsonConfig jsonConfig = new JsonConfig();
        classMap = new HashMap();
        classMap.put("services", StashBoardService.class);

        jsonConfig.setRootClass(StashBoardServices.class);
        jsonConfig.setClassMap(classMap);

        sServices = new StashBoardServices();
        sServices = (StashBoardServices) JSONObject.toBean(prmJSONObject, jsonConfig);

        morpherRegistry = JSONUtils.getMorpherRegistry();
        dynaMorpher = new BeanMorpher(StashBoardService.class, morpherRegistry);
        morpherRegistry.registerMorpher(dynaMorpher);
        services = new ArrayList();
        for (Iterator iter = sServices.getServices().iterator(); iter.hasNext();) {
            services.add(morpherRegistry.morph(StashBoardService.class, iter.next()));
        }
        sServices.setServices(services);
    } catch (Exception ex) {
        Logger.getLogger(StashBoardController.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        return sServices;
    }
}

I have created Beans as follows:

Services:

public class StashBoardServices
{
private List services;

public StashBoardServices()
{

}

public List getServices() {
    return services;
}

public void setServices(List services) {
    this.services = services;
}

}

Service:
package com.StashBoard;

/**
*

  • @author gkhadke
    */
    public class StashBoardService
    {
    private String url;
    private String id;
    private String description;
    private String name;
    private StashBoardCurrentEvent currentevent;

    public StashBoardService()
    {

    }

    public StashBoardCurrentEvent getCurrentevent() {
    return currentevent;
    }

    public void setCurrentevent(StashBoardCurrentEvent currentevent) {
    this.currentevent = currentevent;
    }

    public String getDescription() {
    return description;
    }

    public void setDescription(String description) {
    this.description = description;
    }

    public String getId() {
    return id;
    }

    public void setId(String id) {
    this.id = id;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public String getUrl() {
    return url;
    }

    public void setUrl(String url) {
    this.url = url;
    }

}

and other JAVA bean classes are also defined.

I am getting error since there is "current-event" KV pair in JSONObject response which I can not map to my "currentevent" field in Java Bean.

I wanted to know if there is any annotation support which can resolve this in Json lib?

Transition import from insecure commons-collections to collections4

Version: 3.0.1 and latest 3.0.2 snapshot:

Dependency commons-collections:commons-collections is insecure via https://advisory.checkmarx.net/advisory/vulnerability/Cx78f40514-81ff/

According to documentation https://kordamp.org/json-lib/#_maven json-lib requires: Apache commons-collections4 4.4

So that formally, json-lib does not depend on the insecure package.

However, https://github.com/kordamp/json-lib/blob/master/subprojects/json-lib-core/src/main/java/org/kordamp/json/JsonConfig.java#L20 still points to import org.apache.commons.collections.map.MultiKeyMap;
which instead should be import org.apache.commons.collections4.map.MultiKeyMap;

Currently, I get errors like
NoClassDefFoundError: Could not initialize class org.kordamp.json.JsonConfig
because of that.

Parsing array data with a namespace strips whitespace

The following test case fails,

The difference between this test and testXmlWithSpaceArray which works is the xmlns attribute on the 'e' element.

 public void testXmlWithSpaceArrayNamespace() throws IOException, SAXException,     ParserConfigurationException {
        String xml =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<e xmlns=\"urn:foo-1.0\">\n" +
               "   <c>\n" +
                "      <u>\n" +
                "            <chg>\n" +
                "                  <a>\n" +
                "                      <s>   </s>" +
                "                      <s>   </s>" +
                "                  </a>" +
                "            </chg>\n" +
                "      </u>\n" +
                "   </c>\n" +
                "</e>";

        final XMLSerializer tested = new XMLSerializer();
        //tested.setKeepCData(true);
        tested.setTypeHintsEnabled(false);        
        tested.setRootName("data");

         final JSON jsonRepresentation = tested.read(xml);
        final String jsonText = jsonRepresentation.toString();
        assertTrue(jsonText.contains("[\"   \""));
    }

XMLSerializer setting wrong JSON empty string values

If you take a JSON document with a string key/value pair, where the value is a zero length string:
{"test1": ""}
and convert it to XML with hints enabled it becomes

<o><test1 type=string/><o>

which looks good, but if you then convert the XML back to JSON, the key value pair is returned as an empty array:
{"test1": []}
which is bad.

XMLSerializer is ignoring the type = string attribute when the text length is zero.

This can be fixed by adding code to the isObject() and checkChildElements() functions to check for the string type attribute like:

    String type = getType(element);
    if (type != null && type.equals(JSONTypes.STRING) && !isTopLevel)
        return false;

xml to json array

hi, i have a problem

like this:

<school>
    <students>
        <count>1</count>
        <student>
            <name>stu1</name>
            <id>1</id>
        </student>
    </students>
</school>

I need to convert source to target,Can someone help me?

"school":{
        students:{
            "count":"1",
            "student":[
                {
                    "name":"stu1",
                    "id":"1"
                }
            ]
        }
}

Break codebase into submodules

A few times in the past people have complained that Json-lib brings in too many dependencies due to all the features it contains. Breaking into smaller modules (such as xml, dynabeans, groovy) mitigates the problem. It's probably a good idea to publish an all-modules bundle (BOM perhaps?), for those people that want everything in a single package.

Valid characters for JSON and XML differs: What could be done

Syntax rules for JSON and XMLs are not always compatible.
For example, A JSON data such as {"16x16": "image_url"} can't be converted to <o><16x16>image_url</16x16></o> as XML tag name can't be started with a number.

Is there a workaround for this already in place in the library, if yes what is it? if not what's the expected solution to address such scenarios?

XML Parsing of text with special JSON characters does not work properly

Some cases of XML that contain special JSON characters don't convert to JSON properly

<?xml version="1.0" encoding="UTF-8"?>
<e>
   <c>
      <u>
            <chg>
                  <addr>
                      <street>   </street>                  </addr>            </chg>
      </u>
   </c>
</e>

The spaces in get removed

<?xml version="1.0" encoding="UTF-8"?>
<data><e>{}</e><e>{}</e></data>

The {} is data and should not get stripped by the parser

IllegalStateException when parsing json string to json object

Hello, here is the code snippet:

public boolean Login() {
        JSONObject o = new JSONObject()
                .put("apikey", apiKey)
                .put("username", userName)
                .put("userkey", userKey);
        RequestBody b = RequestBody.create(JSON, o.toString());
        Request r = new Request.Builder()
                .url(endPoint + "login")
                .post(b)
                .build();
        try {
            Response res = client.newCall(r).execute();
            System.out.println(res.body().string());
            JSONObject ro = (JSONObject) JSONSerializer.toJSON(res.body().string()); // Exception happens here
            token = ro.getString("token");
            //...............

prints out:

{
  "token": "eyJhbGciOiJSUzI1NiIsInR5cCI-----------snip----------PWp-6T5I36EYxuzC28IeTEH7XU3mtcdA"
}

Exception happening in: JSONObject ro = (JSONObject) JSONSerializer.toJSON(res.body().string());

java.lang.IllegalStateException: closed
	at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:377)
	at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:371)
	at okhttp3.internal.Util.bomAwareCharset(Util.java:412)
	at okhttp3.ResponseBody.string(ResponseBody.java:173)
	at MyApi.Login(MyApi.java:68)
	at App$1.run(App.java:175)

Is this a problem on my end? The token string is over 520 characters long. might the length be an issue?

Maybe a bug about string null of JSONObject

A json string, maybe the user's name just is null:

{
  "name": "null",
  "mobile": "123"
}

Parsing:

JSONObject json = JSONObject.fromObject(jsonStr);
System.out.println(json.getString("name"));

Output:

“null”

But expected:

null

I read the source code, the string null is considered a JSON, So quote are added to both ends of the string null.

if( quoted && v instanceof String && (JSONUtils.mayBeJSON( (String) v ) || JSONUtils.isFunction( v ))){
       v = JSONUtils.DOUBLE_QUOTE + v + JSONUtils.DOUBLE_QUOTE;
}
public static boolean mayBeJSON( String string ) {
      return string != null
            && ("null".equals( string )
                  || (string.startsWith( "[" ) && string.endsWith( "]" )) || (string.startsWith( "{" ) && string.endsWith( "}" )));
   }

If this is a bug, I am happy to fix it.

Strings that are also valid JSON arrays/objects are deserialized incorrectly

This occurs when the string is nested and more than one level deep, e.g it occurs for
{"a": {"b": "[c-d]"}} but not {"b": "[c-d]"}

I'd expect the string "{"a": {"b": "[c-d]"}}" to be deserialized to:
{
"a" : {
"b" : "[c-d]"
}
}

It's actually deserialized to:
{
"a" : {
"b" : ["c-d"]
}
}

Here's a test for this that currently fails:

   public void testElement_Object_nested() {
      JSONObject jsonObject1 = new JSONObject();
      jsonObject1.element( "str", "\"[]\"" );
      Assertions.assertTrue(jsonObject1.get( "str" ) instanceof String); // This assertion passes
      
      JSONObject jsonObject2 = new JSONObject();
      jsonObject2.element( "obj", jsonObject1);
      Assertions.assertTrue(jsonObject2.getJSONObject( "obj" ).get( "str" ) instanceof String); // This assertion fails
   }

I'm running version 2.4.

Doubt about parsing the string of "null"

Hi Andres @aalmiray, in the latest verion 3.0.0, in function JSONObject.element(key, value), if the input value is a valid JSON formatted string, it will still output a string instead of converting it to JSONObject/JSONArray. But if the string is "null", it will be transformed to a JSONNull, which I think it maybe unreasonable, so I fix it to output the string "null".

public void test_object_element_null_string() {
    JSONObject object = new JSONObject();
    object.element("key1", "{}");
    object.element("key2", "[]");
    object.element("key3", "null");
    Assertions.assertTrue(object.get("key1") instanceof String);
    Assertions.assertTrue(object.get("key2") instanceof String);
    Assertions.assertTrue(object.get("key3") instanceof JSONNull);
    System.out.println(object);

    // {"key1":"{}","key2":"[]","key":null}
    "{}" JSONObject format --> string
    "[]" JSONArray format --> string
    "null" JSONNull formt --> JSONNull
}

However, in function JSONArray.element(), if the string is a valid JSON formatted string, it will be transformed to a JSONArray/JSONObject/JSONNull.

/**
 * Append a String value. This increases the array's length by one.<br>
 * The string may be a valid JSON formatted string, in tha case, it will be
 * transformed to a JSONArray, JSONObject or JSONNull.
 *
 * @param value A String value.
 *
 * @return this.
 */
public JSONArray element(String value) {
    return element(value, new JsonConfig());
}

It is because of this way of handling the input string in JSONArray that we can never get an JSONArray like this: ["null", "string"]...

public void test_array_element_null_string() {
    JSONArray array = new JSONArray();
    array.element("\"null\"");
    array.element("null");
    System.out.println(array);

    // ["\"null\"",null]
}

I wonder why the function of element() in JSONArray and JSONObject handle the input value in diffrent way?

Missing artifact

Try to include it on my POM file as

org.kordamp.json json-lib-core 3.0.2-SNAPSHOT

But am getting this ERROR ::
Missing artifact org.kordamp.json:json-lib-core:jar:3.0.2-SNAPSHOT

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.