kandi background
Explore Kits

JSON-java | A reference implementation of a JSON package in Java. | JSON Processing library

 by   stleary Java Version: 20210307 License: Non-SPDX

 by   stleary Java Version: 20210307 License: Non-SPDX

Download this library from

kandi X-RAY | JSON-java Summary

JSON-java is a Java library typically used in Utilities, JSON Processing applications. JSON-java has no bugs, it has no vulnerabilities, it has build file available and it has medium support. However JSON-java has a Non-SPDX License. You can download it from GitHub.
[JSON](http://www.JSON.org/) is a light-weight language-independent data interchange format. The JSON-Java package is a reference implementation that demonstrates how to parse JSON documents into Java objects and how to generate new JSON documents from the Java classes. Project goals include: * Reliable and consistent results * Adherence to the JSON specification * Easy to build, use, and include in other projects * No external dependencies * Fast execution and low memory footprint * Maintain backward compatibility * Designed and tested to use on Java versions 1.6 - 1.11. The files in this package implement JSON encoders and decoders. The package can also convert between JSON and XML, HTTP headers, Cookies, and CDL. The license includes this restriction: ["The software shall be used for good, not evil."](https://en.wikipedia.org/wiki/Douglas_Crockford#%22Good,_not_Evil%22) If your conscience cannot live with that, then choose a different package. Bug fixes, code improvements, and unit test coverage changes are welcome! Because this project is currently in the maintenance phase, the kinds of changes that can be accepted are limited. For more information, please read the [FAQ](https://github.com/stleary/JSON-java/wiki/FAQ).
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • JSON-java has a medium active ecosystem.
  • It has 3899 star(s) with 2348 fork(s). There are 265 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 15 open issues and 332 have been closed. On average issues are closed in 54 days. There are 1 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of JSON-java is 20210307
JSON-java Support
Best in #JSON Processing
Average in #JSON Processing
JSON-java Support
Best in #JSON Processing
Average in #JSON Processing

quality kandi Quality

  • JSON-java has 0 bugs and 0 code smells.
JSON-java Quality
Best in #JSON Processing
Average in #JSON Processing
JSON-java Quality
Best in #JSON Processing
Average in #JSON Processing

securitySecurity

  • JSON-java has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • JSON-java code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
JSON-java Security
Best in #JSON Processing
Average in #JSON Processing
JSON-java Security
Best in #JSON Processing
Average in #JSON Processing

license License

  • JSON-java has a Non-SPDX License.
  • Non-SPDX licenses can be open source with a non SPDX compliant license, or non open source licenses, and you need to review them closely before use.
JSON-java License
Best in #JSON Processing
Average in #JSON Processing
JSON-java License
Best in #JSON Processing
Average in #JSON Processing

buildReuse

  • JSON-java releases are available to install and integrate.
  • Build file is available. You can build the component from source.
  • Installation instructions, examples and code snippets are available.
JSON-java Reuse
Best in #JSON Processing
Average in #JSON Processing
JSON-java Reuse
Best in #JSON Processing
Average in #JSON Processing
Top functions reviewed by kandi - BETA

kandi has reviewed JSON-java and discovered the below as its top functions. This is intended to give you an instant insight into JSON-java implemented functionality, and help decide if they suit your requirements.

  • Parse a JSON token .
  • Skip characters from to to string .
  • Convert a string to a number .
  • Get the next string .
  • Get the next value .
  • Serialize a JSON object to a JSON string .
  • Emit a new key .
  • Return the next token .
  • Adds the contents of an array to this JSONArray .
  • Unescapes a string .

JSON-java Key Features

A reference implementation of a JSON package in Java.

Build Instructions

copy iconCopydownload iconDownload
mvn clean test

Notes

copy iconCopydownload iconDownload
SomeBean[] myArr = new SomeBean[]{ new SomeBean(1), new SomeBean(2) };
// these will be wrapped
JSONArray jArr = new JSONArray(myArr);
// these will not be wrapped
jArr.putAll(new SomeBean[]{ new SomeBean(3), new SomeBean(4) });

Check if JSONObject matches JSON boolean expression

copy iconCopydownload iconDownload
import org.json.*;

import java.io.*;
import java.nio.file.*;
import java.util.List;
import java.util.stream.*;

import static java.util.stream.Collectors.toList;

public class Test {

    public static void main(String[] args) throws IOException {
        final List<JSONObject> jsObjs =
                stream(readJsonArray("users.json"))
                        .map(JSONObject.class::cast)
                        .collect(toList());

        final JSONObject jsFilter = readJsonObject("filter.json");

        final List<JSONObject> matches = applyFilter(jsObjs, jsFilter);

        System.out.println(matches);
    }

    private static List<JSONObject> applyFilter(List<JSONObject> jsObjs, JSONObject jsFilter) {
        return jsObjs.stream()
                .filter(jsObj -> match(jsObj, jsFilter))
                .collect(toList());
    }

    private static boolean match(JSONObject jsObj, JSONObject jsFilter) {

        final String name = getSingleKey(jsFilter);
        final Object value = jsFilter.get(name);

        switch (name) {
            case "AND":
                return stream((JSONArray)value)
                        .map(JSONObject.class::cast)
                        .allMatch(jse -> match(jsObj, jse));
            case "OR":
                return stream((JSONArray)value)
                        .map(JSONObject.class::cast)
                        .anyMatch(jse -> match(jsObj, jse));
            case "NOT":
                return !match(jsObj, (JSONObject)((JSONArray)value).get(0));
            default:
                final JSONObject jsOp = (JSONObject)value;
                final String operator = getSingleKey(jsOp);
                final Object operand = jsOp.get(operator);
                switch (operator) {
                    case "eq": return jsObj.get(name).equals(operand);
                    case "lt": return (Integer)jsObj.get(name) < (Integer)operand;
                    case "gt": return (Integer)jsObj.get(name) > (Integer)operand;
                    default: throw new IllegalArgumentException("Unexpected operator: " + operator);
                }
        }
    }

    private static JSONObject readJsonObject(String fileName) throws IOException {
        try (Reader reader = Files.newBufferedReader(Paths.get(fileName))) {
            return new JSONObject(new JSONTokener(reader));
        }
    }

    private static JSONArray readJsonArray(String fileName) throws IOException {
        try (Reader reader = Files.newBufferedReader(Paths.get(fileName))) {
            return new JSONArray(new JSONTokener(reader));
        }
    }

    private static Stream<Object> stream(JSONArray jsa) {
        return StreamSupport.stream(jsa.spliterator(), false);
    }

    private static String getSingleKey(JSONObject jso) {
        if (jso.length() != 1) {
            throw new IllegalArgumentException("Expected single entry");
        } else {
            return jso.keySet().iterator().next();
        }
    }
}

Does it matter if function returns T or object if T can not be inferred from context?

copy iconCopydownload iconDownload
public class MyClass {
    public static void main(String args[]) {
        String result1 = MyClass.test(); // works as expected
        Object result2 = MyClass.<Integer>test(); // works "surprisingly"
        int result3 = MyClass.test(); // cannot be cast to java.lang.Integer
    }
    
    static <T> T test() {
        try {
            return (T) "Hello World";
        } catch (ClassCastException e) {
            throw new Error(); // never reached
        }
    }
}

How to import json array into java program using JSON.ORG

copy iconCopydownload iconDownload
JSONTokener jsonToken = new JSONTokener(new FileReader(fileName));
JSONArray jsonArray = new JSONArray(jsonToken);
System.out.println(jsonArray.toString());
System.out.println(jsonArray.get(0));
[{"priceChange":"-0.00029700","symbol":"ETHBTC"},{"priceChange":"-0.00003300","symbol":"LTCBTC"}]
{"priceChange":"-0.00029700","symbol":"ETHBTC"}
-----------------------
JSONTokener jsonToken = new JSONTokener(new FileReader(fileName));
JSONArray jsonArray = new JSONArray(jsonToken);
System.out.println(jsonArray.toString());
System.out.println(jsonArray.get(0));
[{"priceChange":"-0.00029700","symbol":"ETHBTC"},{"priceChange":"-0.00003300","symbol":"LTCBTC"}]
{"priceChange":"-0.00029700","symbol":"ETHBTC"}

org.json cannot be resolved to a module?

copy iconCopydownload iconDownload
…
<dependencies>
    <dependency>
       <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20200518</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>11</source>
                <target>11</target>
                <compilerArgs>
                    <arg>-Xlint:unchecked</arg>
                    <arg>--add-modules</arg>
                    <arg>org.json</arg>
                </compilerArgs>
            </configuration>
        </plugin>
    </plugins>
</build>
…

Filtering nested js object array using javascript

copy iconCopydownload iconDownload
var data = [
  [{
      "Id": "123",
      "Name": "Abc",
      "Amount": 110000
    },
    {
      "Id": "567",
      "Name": "DEF",
      "Amount": 98000
    },
    {
      "Id": "345",
      "Name": "XYZ",
      "Amount": 145000
    }
  ],
  [{
      "Id": "656",
      "Name": "Abc",
      "Amount": 110000
    },
    {
      "Id": "223",
      "Name": "DEF",
      "Amount": 98000
    },
    {
      "Id": "897",
      "Name": "XYZ",
      "Amount": 145000
    }
  ]
];


var result = data.flat().filter(element => element.Id == "223");
console.log(result);

console.log(data.find(el => el.find(item => item.Id === "223")))
-----------------------
let result = data.map( array =>  
   array.filter( item => item.Id === "223" )
).flat();
var data = 
    [ [ { Id: '123', Name: 'Abc', Amount: 110000 } 
      , { Id: '567', Name: 'DEF', Amount:  98000 } 
      , { Id: '345', Name: 'XYZ', Amount: 145000 } 
      ] 
    , [ { Id: '656', Name: 'Abc', Amount: 110000 } 
      , { Id: '223', Name: 'DEF', Amount:  98000 } 
      , { Id: '897', Name: 'XYZ', Amount: 145000 } 
    ] ];

let result = data.map( array =>  array.filter( item => item.Id === "223" )).flat();


console.log(result);
-----------------------
let result = data.map( array =>  
   array.filter( item => item.Id === "223" )
).flat();
var data = 
    [ [ { Id: '123', Name: 'Abc', Amount: 110000 } 
      , { Id: '567', Name: 'DEF', Amount:  98000 } 
      , { Id: '345', Name: 'XYZ', Amount: 145000 } 
      ] 
    , [ { Id: '656', Name: 'Abc', Amount: 110000 } 
      , { Id: '223', Name: 'DEF', Amount:  98000 } 
      , { Id: '897', Name: 'XYZ', Amount: 145000 } 
    ] ];

let result = data.map( array =>  array.filter( item => item.Id === "223" )).flat();


console.log(result);

Converting byte[] to json and vice versa without jackson or gson

copy iconCopydownload iconDownload
public static void main(String[] args) {
    Data data = new Data(11, 12);
    String json = toJson(data);
    System.out.println(json);

    byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
    Data res = toDataObj(bytes);
    System.out.println(res.a);
    System.out.println(res.b);
}

public static String toJson(Data data) {
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("a", data.a);
    jsonObj.put("b", data.b);
    return jsonObj.toString();
}


public static Data toDataObj(byte[] bytesClass) {
    JSONObject jsonObject = new JSONObject(new String(bytesClass, StandardCharsets.UTF_8));
    Data data = new Data(0, 0);
    data.a = jsonObject.getInt("a");
    data.b = jsonObject.getInt("b");
    return data;
}

public static class Data {

    int a;
    int b;

    public Data(int a, int b) {
        this.a = a;
        this.b = b;
    }
}

LocalDateTime is representing in array format

copy iconCopydownload iconDownload
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
    return builder -> {
        builder.simpleDateFormat(dateTimeFormat);
        builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(dateFormat)));
        builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
    };
}

Convert Excel to JSON - using React-Dropzone (client side probably)

copy iconCopydownload iconDownload
  const handleExcelDrop = (acceptedFiles) => {
    console.log("handleExcelDrop")
    setFileNames(acceptedFiles.map(file => file.name));
     acceptedFiles.forEach((file) => {
        console.log("handleExcelDrop:forEach(file)")
        // See https://stackoverflow.com/questions/30859901/parse-xlsx-with-node-and-create-json 
        const reader = new FileReader() 
        const rABS = !!reader.readAsBinaryString;  // !! converts object to boolean 
        reader.onabort = () => console.log('file reading was aborted')
        reader.onerror = () => console.log('file reading has failed')
        reader.onload = (e) => {
            // Do what you want with the file contents 
            var bstr = e.target.result; 
            var workbook = XLSX.read(bstr, { type: rABS ? "binary" : "array" })
            var sheet_name_list = workbook.SheetNames[0];
            var jsonFromExcel = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list], {
                raw: false,
                dateNF: "MM-DD-YYYY",
                header:1,
                defval: ""
            })
            console.log("jsonFromExcel object=")
            console.log(jsonFromExcel)
            console.log("jsonFromExcel string=")
            console.log(JSON.stringify(jsonFromExcel))

            fetch('http://localhost:3001/api/filedataExcel', {
              method: 'POST',
              headers: {
                 'Accept': 'application/json',
                 'Content-Type': 'application/json'
              },
              // TODO - could add userid, datetime here, filename, etc...  
              jsonFromExcel
            })

          }
          if (rABS) reader.readAsBinaryString(file);
          else reader.readAsArrayBuffer(file);
     })
  }
import XLSX from 'xlsx' 
-----------------------
  const handleExcelDrop = (acceptedFiles) => {
    console.log("handleExcelDrop")
    setFileNames(acceptedFiles.map(file => file.name));
     acceptedFiles.forEach((file) => {
        console.log("handleExcelDrop:forEach(file)")
        // See https://stackoverflow.com/questions/30859901/parse-xlsx-with-node-and-create-json 
        const reader = new FileReader() 
        const rABS = !!reader.readAsBinaryString;  // !! converts object to boolean 
        reader.onabort = () => console.log('file reading was aborted')
        reader.onerror = () => console.log('file reading has failed')
        reader.onload = (e) => {
            // Do what you want with the file contents 
            var bstr = e.target.result; 
            var workbook = XLSX.read(bstr, { type: rABS ? "binary" : "array" })
            var sheet_name_list = workbook.SheetNames[0];
            var jsonFromExcel = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list], {
                raw: false,
                dateNF: "MM-DD-YYYY",
                header:1,
                defval: ""
            })
            console.log("jsonFromExcel object=")
            console.log(jsonFromExcel)
            console.log("jsonFromExcel string=")
            console.log(JSON.stringify(jsonFromExcel))

            fetch('http://localhost:3001/api/filedataExcel', {
              method: 'POST',
              headers: {
                 'Accept': 'application/json',
                 'Content-Type': 'application/json'
              },
              // TODO - could add userid, datetime here, filename, etc...  
              jsonFromExcel
            })

          }
          if (rABS) reader.readAsBinaryString(file);
          else reader.readAsArrayBuffer(file);
     })
  }
import XLSX from 'xlsx' 

How do I read this Generics correctly from JSON?

copy iconCopydownload iconDownload
Type safety: The expression of type JSONContainer needs unchecked conversion to conform to JSONContainer
...Communicator.java uses unchecked or unsafe operations.
...Recompile with -Xlint:unchecked for details.
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
com.badlogic.gdx.utils.SerializationException: Field not found: cid (java.lang.Object)...
...
private static final String JADEN_AS_JSON = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}";

private static final String JADEN_FAILS_AS_ACTOR = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HasBeen, cid:{oid:129} }}";

static public void main( String ... args ){
    
    out.printf( "%1$22s%n", "foo");
    
    JSONContainer< CommonNoun > wtf = new JSONContainer< > ( );
    
    CommonNoun wtBrattyF = new CommonNoun( "Jaden Pinkett Smith", "Hollywood", "HasBeen" );
    
    wtf.setJden( wtBrattyF );
    
    out.printf( "%1$42s%n", wtf );
    
    Json jden = new Json();
    
    out.printf("%1$59s%n", jden.toJson( wtf ) );
            
    JSONContainer wtReifiableF = jden.fromJson(JSONContainer.class, JADEN_AS_JSON); /* This is fine */        
    
    out.printf("%1$59s%n", jden.toJson( wtReifiableF ) );
            
    JSONContainer/*< CommonNoun >*/ wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_AS_JSON );
    
    wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_FAILS_AS_ACTOR ); /* This causes the error you reported */
}
...
JSONContainer [ jden: CommonNoun [ person: Jaden Pinkett Smith, place: Hollywood, thing: HasBeen ] ]
{jden:{class:CommonNoun,person:Jaden Pinkett Smith,place:Hollywood,thing:HasBeen}}
{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}

Exception in thread "main" com.badlogic.gdx.utils.SerializationException: Field not found: cid (CommonNoun)
Serialization trace:
{}.jden.cid
jden (JSONContainer)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:893)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:902)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.fromJson(Json.java:829)
    at DeduperAnswer.main(DeduperAnswer.java:33)
public class Cid { 
    
    int oid;        

    /* ... getter and setter elided ... */
}
public class CommonNoun { 
    
    Cid cid;
    
    String name;
    
    int form;

    /* ... getters and setters elided ... */
}
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
{myObject:{class:CommonNoun,cid:{oid:139},name:Jada Pinkett Smith,form:69},children:[{myObject:{class:CommonNoun,cid:{oid:666},name:Jaden Pinkett Smith,form:-666},children:[]},{myObject:{class:CommonNoun,cid:{oid:69},name:Willow Pinkett Smith,form:69},children:[]}]}
-----------------------
Type safety: The expression of type JSONContainer needs unchecked conversion to conform to JSONContainer
...Communicator.java uses unchecked or unsafe operations.
...Recompile with -Xlint:unchecked for details.
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
com.badlogic.gdx.utils.SerializationException: Field not found: cid (java.lang.Object)...
...
private static final String JADEN_AS_JSON = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}";

private static final String JADEN_FAILS_AS_ACTOR = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HasBeen, cid:{oid:129} }}";

static public void main( String ... args ){
    
    out.printf( "%1$22s%n", "foo");
    
    JSONContainer< CommonNoun > wtf = new JSONContainer< > ( );
    
    CommonNoun wtBrattyF = new CommonNoun( "Jaden Pinkett Smith", "Hollywood", "HasBeen" );
    
    wtf.setJden( wtBrattyF );
    
    out.printf( "%1$42s%n", wtf );
    
    Json jden = new Json();
    
    out.printf("%1$59s%n", jden.toJson( wtf ) );
            
    JSONContainer wtReifiableF = jden.fromJson(JSONContainer.class, JADEN_AS_JSON); /* This is fine */        
    
    out.printf("%1$59s%n", jden.toJson( wtReifiableF ) );
            
    JSONContainer/*< CommonNoun >*/ wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_AS_JSON );
    
    wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_FAILS_AS_ACTOR ); /* This causes the error you reported */
}
...
JSONContainer [ jden: CommonNoun [ person: Jaden Pinkett Smith, place: Hollywood, thing: HasBeen ] ]
{jden:{class:CommonNoun,person:Jaden Pinkett Smith,place:Hollywood,thing:HasBeen}}
{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}

Exception in thread "main" com.badlogic.gdx.utils.SerializationException: Field not found: cid (CommonNoun)
Serialization trace:
{}.jden.cid
jden (JSONContainer)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:893)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:902)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.fromJson(Json.java:829)
    at DeduperAnswer.main(DeduperAnswer.java:33)
public class Cid { 
    
    int oid;        

    /* ... getter and setter elided ... */
}
public class CommonNoun { 
    
    Cid cid;
    
    String name;
    
    int form;

    /* ... getters and setters elided ... */
}
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
{myObject:{class:CommonNoun,cid:{oid:139},name:Jada Pinkett Smith,form:69},children:[{myObject:{class:CommonNoun,cid:{oid:666},name:Jaden Pinkett Smith,form:-666},children:[]},{myObject:{class:CommonNoun,cid:{oid:69},name:Willow Pinkett Smith,form:69},children:[]}]}
-----------------------
Type safety: The expression of type JSONContainer needs unchecked conversion to conform to JSONContainer
...Communicator.java uses unchecked or unsafe operations.
...Recompile with -Xlint:unchecked for details.
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
com.badlogic.gdx.utils.SerializationException: Field not found: cid (java.lang.Object)...
...
private static final String JADEN_AS_JSON = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}";

private static final String JADEN_FAILS_AS_ACTOR = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HasBeen, cid:{oid:129} }}";

static public void main( String ... args ){
    
    out.printf( "%1$22s%n", "foo");
    
    JSONContainer< CommonNoun > wtf = new JSONContainer< > ( );
    
    CommonNoun wtBrattyF = new CommonNoun( "Jaden Pinkett Smith", "Hollywood", "HasBeen" );
    
    wtf.setJden( wtBrattyF );
    
    out.printf( "%1$42s%n", wtf );
    
    Json jden = new Json();
    
    out.printf("%1$59s%n", jden.toJson( wtf ) );
            
    JSONContainer wtReifiableF = jden.fromJson(JSONContainer.class, JADEN_AS_JSON); /* This is fine */        
    
    out.printf("%1$59s%n", jden.toJson( wtReifiableF ) );
            
    JSONContainer/*< CommonNoun >*/ wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_AS_JSON );
    
    wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_FAILS_AS_ACTOR ); /* This causes the error you reported */
}
...
JSONContainer [ jden: CommonNoun [ person: Jaden Pinkett Smith, place: Hollywood, thing: HasBeen ] ]
{jden:{class:CommonNoun,person:Jaden Pinkett Smith,place:Hollywood,thing:HasBeen}}
{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}

Exception in thread "main" com.badlogic.gdx.utils.SerializationException: Field not found: cid (CommonNoun)
Serialization trace:
{}.jden.cid
jden (JSONContainer)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:893)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:902)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.fromJson(Json.java:829)
    at DeduperAnswer.main(DeduperAnswer.java:33)
public class Cid { 
    
    int oid;        

    /* ... getter and setter elided ... */
}
public class CommonNoun { 
    
    Cid cid;
    
    String name;
    
    int form;

    /* ... getters and setters elided ... */
}
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
{myObject:{class:CommonNoun,cid:{oid:139},name:Jada Pinkett Smith,form:69},children:[{myObject:{class:CommonNoun,cid:{oid:666},name:Jaden Pinkett Smith,form:-666},children:[]},{myObject:{class:CommonNoun,cid:{oid:69},name:Willow Pinkett Smith,form:69},children:[]}]}
-----------------------
Type safety: The expression of type JSONContainer needs unchecked conversion to conform to JSONContainer
...Communicator.java uses unchecked or unsafe operations.
...Recompile with -Xlint:unchecked for details.
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
com.badlogic.gdx.utils.SerializationException: Field not found: cid (java.lang.Object)...
...
private static final String JADEN_AS_JSON = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}";

private static final String JADEN_FAILS_AS_ACTOR = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HasBeen, cid:{oid:129} }}";

static public void main( String ... args ){
    
    out.printf( "%1$22s%n", "foo");
    
    JSONContainer< CommonNoun > wtf = new JSONContainer< > ( );
    
    CommonNoun wtBrattyF = new CommonNoun( "Jaden Pinkett Smith", "Hollywood", "HasBeen" );
    
    wtf.setJden( wtBrattyF );
    
    out.printf( "%1$42s%n", wtf );
    
    Json jden = new Json();
    
    out.printf("%1$59s%n", jden.toJson( wtf ) );
            
    JSONContainer wtReifiableF = jden.fromJson(JSONContainer.class, JADEN_AS_JSON); /* This is fine */        
    
    out.printf("%1$59s%n", jden.toJson( wtReifiableF ) );
            
    JSONContainer/*< CommonNoun >*/ wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_AS_JSON );
    
    wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_FAILS_AS_ACTOR ); /* This causes the error you reported */
}
...
JSONContainer [ jden: CommonNoun [ person: Jaden Pinkett Smith, place: Hollywood, thing: HasBeen ] ]
{jden:{class:CommonNoun,person:Jaden Pinkett Smith,place:Hollywood,thing:HasBeen}}
{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}

Exception in thread "main" com.badlogic.gdx.utils.SerializationException: Field not found: cid (CommonNoun)
Serialization trace:
{}.jden.cid
jden (JSONContainer)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:893)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:902)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.fromJson(Json.java:829)
    at DeduperAnswer.main(DeduperAnswer.java:33)
public class Cid { 
    
    int oid;        

    /* ... getter and setter elided ... */
}
public class CommonNoun { 
    
    Cid cid;
    
    String name;
    
    int form;

    /* ... getters and setters elided ... */
}
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
{myObject:{class:CommonNoun,cid:{oid:139},name:Jada Pinkett Smith,form:69},children:[{myObject:{class:CommonNoun,cid:{oid:666},name:Jaden Pinkett Smith,form:-666},children:[]},{myObject:{class:CommonNoun,cid:{oid:69},name:Willow Pinkett Smith,form:69},children:[]}]}
-----------------------
Type safety: The expression of type JSONContainer needs unchecked conversion to conform to JSONContainer
...Communicator.java uses unchecked or unsafe operations.
...Recompile with -Xlint:unchecked for details.
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
com.badlogic.gdx.utils.SerializationException: Field not found: cid (java.lang.Object)...
...
private static final String JADEN_AS_JSON = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}";

private static final String JADEN_FAILS_AS_ACTOR = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HasBeen, cid:{oid:129} }}";

static public void main( String ... args ){
    
    out.printf( "%1$22s%n", "foo");
    
    JSONContainer< CommonNoun > wtf = new JSONContainer< > ( );
    
    CommonNoun wtBrattyF = new CommonNoun( "Jaden Pinkett Smith", "Hollywood", "HasBeen" );
    
    wtf.setJden( wtBrattyF );
    
    out.printf( "%1$42s%n", wtf );
    
    Json jden = new Json();
    
    out.printf("%1$59s%n", jden.toJson( wtf ) );
            
    JSONContainer wtReifiableF = jden.fromJson(JSONContainer.class, JADEN_AS_JSON); /* This is fine */        
    
    out.printf("%1$59s%n", jden.toJson( wtReifiableF ) );
            
    JSONContainer/*< CommonNoun >*/ wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_AS_JSON );
    
    wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_FAILS_AS_ACTOR ); /* This causes the error you reported */
}
...
JSONContainer [ jden: CommonNoun [ person: Jaden Pinkett Smith, place: Hollywood, thing: HasBeen ] ]
{jden:{class:CommonNoun,person:Jaden Pinkett Smith,place:Hollywood,thing:HasBeen}}
{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}

Exception in thread "main" com.badlogic.gdx.utils.SerializationException: Field not found: cid (CommonNoun)
Serialization trace:
{}.jden.cid
jden (JSONContainer)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:893)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:902)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.fromJson(Json.java:829)
    at DeduperAnswer.main(DeduperAnswer.java:33)
public class Cid { 
    
    int oid;        

    /* ... getter and setter elided ... */
}
public class CommonNoun { 
    
    Cid cid;
    
    String name;
    
    int form;

    /* ... getters and setters elided ... */
}
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
{myObject:{class:CommonNoun,cid:{oid:139},name:Jada Pinkett Smith,form:69},children:[{myObject:{class:CommonNoun,cid:{oid:666},name:Jaden Pinkett Smith,form:-666},children:[]},{myObject:{class:CommonNoun,cid:{oid:69},name:Willow Pinkett Smith,form:69},children:[]}]}
-----------------------
Type safety: The expression of type JSONContainer needs unchecked conversion to conform to JSONContainer
...Communicator.java uses unchecked or unsafe operations.
...Recompile with -Xlint:unchecked for details.
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
com.badlogic.gdx.utils.SerializationException: Field not found: cid (java.lang.Object)...
...
private static final String JADEN_AS_JSON = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}";

private static final String JADEN_FAILS_AS_ACTOR = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HasBeen, cid:{oid:129} }}";

static public void main( String ... args ){
    
    out.printf( "%1$22s%n", "foo");
    
    JSONContainer< CommonNoun > wtf = new JSONContainer< > ( );
    
    CommonNoun wtBrattyF = new CommonNoun( "Jaden Pinkett Smith", "Hollywood", "HasBeen" );
    
    wtf.setJden( wtBrattyF );
    
    out.printf( "%1$42s%n", wtf );
    
    Json jden = new Json();
    
    out.printf("%1$59s%n", jden.toJson( wtf ) );
            
    JSONContainer wtReifiableF = jden.fromJson(JSONContainer.class, JADEN_AS_JSON); /* This is fine */        
    
    out.printf("%1$59s%n", jden.toJson( wtReifiableF ) );
            
    JSONContainer/*< CommonNoun >*/ wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_AS_JSON );
    
    wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_FAILS_AS_ACTOR ); /* This causes the error you reported */
}
...
JSONContainer [ jden: CommonNoun [ person: Jaden Pinkett Smith, place: Hollywood, thing: HasBeen ] ]
{jden:{class:CommonNoun,person:Jaden Pinkett Smith,place:Hollywood,thing:HasBeen}}
{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}

Exception in thread "main" com.badlogic.gdx.utils.SerializationException: Field not found: cid (CommonNoun)
Serialization trace:
{}.jden.cid
jden (JSONContainer)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:893)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:902)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.fromJson(Json.java:829)
    at DeduperAnswer.main(DeduperAnswer.java:33)
public class Cid { 
    
    int oid;        

    /* ... getter and setter elided ... */
}
public class CommonNoun { 
    
    Cid cid;
    
    String name;
    
    int form;

    /* ... getters and setters elided ... */
}
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
{myObject:{class:CommonNoun,cid:{oid:139},name:Jada Pinkett Smith,form:69},children:[{myObject:{class:CommonNoun,cid:{oid:666},name:Jaden Pinkett Smith,form:-666},children:[]},{myObject:{class:CommonNoun,cid:{oid:69},name:Willow Pinkett Smith,form:69},children:[]}]}
-----------------------
Type safety: The expression of type JSONContainer needs unchecked conversion to conform to JSONContainer
...Communicator.java uses unchecked or unsafe operations.
...Recompile with -Xlint:unchecked for details.
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
com.badlogic.gdx.utils.SerializationException: Field not found: cid (java.lang.Object)...
...
private static final String JADEN_AS_JSON = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}";

private static final String JADEN_FAILS_AS_ACTOR = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HasBeen, cid:{oid:129} }}";

static public void main( String ... args ){
    
    out.printf( "%1$22s%n", "foo");
    
    JSONContainer< CommonNoun > wtf = new JSONContainer< > ( );
    
    CommonNoun wtBrattyF = new CommonNoun( "Jaden Pinkett Smith", "Hollywood", "HasBeen" );
    
    wtf.setJden( wtBrattyF );
    
    out.printf( "%1$42s%n", wtf );
    
    Json jden = new Json();
    
    out.printf("%1$59s%n", jden.toJson( wtf ) );
            
    JSONContainer wtReifiableF = jden.fromJson(JSONContainer.class, JADEN_AS_JSON); /* This is fine */        
    
    out.printf("%1$59s%n", jden.toJson( wtReifiableF ) );
            
    JSONContainer/*< CommonNoun >*/ wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_AS_JSON );
    
    wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_FAILS_AS_ACTOR ); /* This causes the error you reported */
}
...
JSONContainer [ jden: CommonNoun [ person: Jaden Pinkett Smith, place: Hollywood, thing: HasBeen ] ]
{jden:{class:CommonNoun,person:Jaden Pinkett Smith,place:Hollywood,thing:HasBeen}}
{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}

Exception in thread "main" com.badlogic.gdx.utils.SerializationException: Field not found: cid (CommonNoun)
Serialization trace:
{}.jden.cid
jden (JSONContainer)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:893)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:902)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.fromJson(Json.java:829)
    at DeduperAnswer.main(DeduperAnswer.java:33)
public class Cid { 
    
    int oid;        

    /* ... getter and setter elided ... */
}
public class CommonNoun { 
    
    Cid cid;
    
    String name;
    
    int form;

    /* ... getters and setters elided ... */
}
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
{myObject:{class:CommonNoun,cid:{oid:139},name:Jada Pinkett Smith,form:69},children:[{myObject:{class:CommonNoun,cid:{oid:666},name:Jaden Pinkett Smith,form:-666},children:[]},{myObject:{class:CommonNoun,cid:{oid:69},name:Willow Pinkett Smith,form:69},children:[]}]}
-----------------------
Type safety: The expression of type JSONContainer needs unchecked conversion to conform to JSONContainer
...Communicator.java uses unchecked or unsafe operations.
...Recompile with -Xlint:unchecked for details.
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
com.badlogic.gdx.utils.SerializationException: Field not found: cid (java.lang.Object)...
...
private static final String JADEN_AS_JSON = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}";

private static final String JADEN_FAILS_AS_ACTOR = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HasBeen, cid:{oid:129} }}";

static public void main( String ... args ){
    
    out.printf( "%1$22s%n", "foo");
    
    JSONContainer< CommonNoun > wtf = new JSONContainer< > ( );
    
    CommonNoun wtBrattyF = new CommonNoun( "Jaden Pinkett Smith", "Hollywood", "HasBeen" );
    
    wtf.setJden( wtBrattyF );
    
    out.printf( "%1$42s%n", wtf );
    
    Json jden = new Json();
    
    out.printf("%1$59s%n", jden.toJson( wtf ) );
            
    JSONContainer wtReifiableF = jden.fromJson(JSONContainer.class, JADEN_AS_JSON); /* This is fine */        
    
    out.printf("%1$59s%n", jden.toJson( wtReifiableF ) );
            
    JSONContainer/*< CommonNoun >*/ wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_AS_JSON );
    
    wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_FAILS_AS_ACTOR ); /* This causes the error you reported */
}
...
JSONContainer [ jden: CommonNoun [ person: Jaden Pinkett Smith, place: Hollywood, thing: HasBeen ] ]
{jden:{class:CommonNoun,person:Jaden Pinkett Smith,place:Hollywood,thing:HasBeen}}
{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}

Exception in thread "main" com.badlogic.gdx.utils.SerializationException: Field not found: cid (CommonNoun)
Serialization trace:
{}.jden.cid
jden (JSONContainer)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:893)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:902)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.fromJson(Json.java:829)
    at DeduperAnswer.main(DeduperAnswer.java:33)
public class Cid { 
    
    int oid;        

    /* ... getter and setter elided ... */
}
public class CommonNoun { 
    
    Cid cid;
    
    String name;
    
    int form;

    /* ... getters and setters elided ... */
}
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
{myObject:{class:CommonNoun,cid:{oid:139},name:Jada Pinkett Smith,form:69},children:[{myObject:{class:CommonNoun,cid:{oid:666},name:Jaden Pinkett Smith,form:-666},children:[]},{myObject:{class:CommonNoun,cid:{oid:69},name:Willow Pinkett Smith,form:69},children:[]}]}
-----------------------
Type safety: The expression of type JSONContainer needs unchecked conversion to conform to JSONContainer
...Communicator.java uses unchecked or unsafe operations.
...Recompile with -Xlint:unchecked for details.
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
com.badlogic.gdx.utils.SerializationException: Field not found: cid (java.lang.Object)...
...
private static final String JADEN_AS_JSON = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}";

private static final String JADEN_FAILS_AS_ACTOR = "{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HasBeen, cid:{oid:129} }}";

static public void main( String ... args ){
    
    out.printf( "%1$22s%n", "foo");
    
    JSONContainer< CommonNoun > wtf = new JSONContainer< > ( );
    
    CommonNoun wtBrattyF = new CommonNoun( "Jaden Pinkett Smith", "Hollywood", "HasBeen" );
    
    wtf.setJden( wtBrattyF );
    
    out.printf( "%1$42s%n", wtf );
    
    Json jden = new Json();
    
    out.printf("%1$59s%n", jden.toJson( wtf ) );
            
    JSONContainer wtReifiableF = jden.fromJson(JSONContainer.class, JADEN_AS_JSON); /* This is fine */        
    
    out.printf("%1$59s%n", jden.toJson( wtReifiableF ) );
            
    JSONContainer/*< CommonNoun >*/ wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_AS_JSON );
    
    wtUnReifiableF = jden.fromJson( JSONContainer.class, JADEN_FAILS_AS_ACTOR ); /* This causes the error you reported */
}
...
JSONContainer [ jden: CommonNoun [ person: Jaden Pinkett Smith, place: Hollywood, thing: HasBeen ] ]
{jden:{class:CommonNoun,person:Jaden Pinkett Smith,place:Hollywood,thing:HasBeen}}
{jden:{class:CommonNoun,person:Jaden,place:Hollywood,thing:HashBeen}}

Exception in thread "main" com.badlogic.gdx.utils.SerializationException: Field not found: cid (CommonNoun)
Serialization trace:
{}.jden.cid
jden (JSONContainer)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:893)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.readFields(Json.java:902)
    at com.badlogic.gdx.utils.Json.readValue(Json.java:1074)
    at com.badlogic.gdx.utils.Json.fromJson(Json.java:829)
    at DeduperAnswer.main(DeduperAnswer.java:33)
public class Cid { 
    
    int oid;        

    /* ... getter and setter elided ... */
}
public class CommonNoun { 
    
    Cid cid;
    
    String name;
    
    int form;

    /* ... getters and setters elided ... */
}
result = {"myObject":{"cid":{"oid":129},"name":"technology","form":1},"children":[]}
{myObject:{class:CommonNoun,cid:{oid:139},name:Jada Pinkett Smith,form:69},children:[{myObject:{class:CommonNoun,cid:{oid:666},name:Jaden Pinkett Smith,form:-666},children:[]},{myObject:{class:CommonNoun,cid:{oid:69},name:Willow Pinkett Smith,form:69},children:[]}]}

Add a JSONObject/String to a TreeView using JavaFx

copy iconCopydownload iconDownload
@SuppressWarnings("unchecked")
private static TreeItem<String> parseJSON(String name, Object json) {
    TreeItem<String> item = new TreeItem<>();
    if (json instanceof JSONObject) {
        item.setValue(name);
        JSONObject object = (JSONObject) json;
        ((Set<Map.Entry>) object.entrySet()).forEach(entry -> {
            String childName = (String) entry.getKey();
            Object childJson = entry.getValue();
            TreeItem<String> child = parseJSON(childName, childJson);
            item.getChildren().add(child);
        });
    } else if (json instanceof JSONArray) {
        item.setValue(name);
        JSONArray array = (JSONArray) json;
        for (int i = 0; i < array.size(); i++) {
            String childName = String.valueOf(i);
            Object childJson = array.get(i);
            TreeItem<String> child = parseJSON(childName, childJson);
            item.getChildren().add(child);
        }
    } else {
        item.setValue(name + " : " + json);
    }
    return item;
}
JSONParser parser = new JSONParser();
JSONObject root = (JSONObject) parser.parse(new FileReader(new File("json_file_path")));

TreeView<String> treeView = new TreeView<>();
treeView.setRoot(parseJSON("root_object", root));
-----------------------
@SuppressWarnings("unchecked")
private static TreeItem<String> parseJSON(String name, Object json) {
    TreeItem<String> item = new TreeItem<>();
    if (json instanceof JSONObject) {
        item.setValue(name);
        JSONObject object = (JSONObject) json;
        ((Set<Map.Entry>) object.entrySet()).forEach(entry -> {
            String childName = (String) entry.getKey();
            Object childJson = entry.getValue();
            TreeItem<String> child = parseJSON(childName, childJson);
            item.getChildren().add(child);
        });
    } else if (json instanceof JSONArray) {
        item.setValue(name);
        JSONArray array = (JSONArray) json;
        for (int i = 0; i < array.size(); i++) {
            String childName = String.valueOf(i);
            Object childJson = array.get(i);
            TreeItem<String> child = parseJSON(childName, childJson);
            item.getChildren().add(child);
        }
    } else {
        item.setValue(name + " : " + json);
    }
    return item;
}
JSONParser parser = new JSONParser();
JSONObject root = (JSONObject) parser.parse(new FileReader(new File("json_file_path")));

TreeView<String> treeView = new TreeView<>();
treeView.setRoot(parseJSON("root_object", root));

Community Discussions

Trending Discussions on JSON-java
  • Check if JSONObject matches JSON boolean expression
  • Does it matter if function returns T or object if T can not be inferred from context?
  • How to import json array into java program using JSON.ORG
  • org.json cannot be resolved to a module?
  • Filtering nested js object array using javascript
  • Converting byte[] to json and vice versa without jackson or gson
  • LocalDateTime is representing in array format
  • Convert Excel to JSON - using React-Dropzone (client side probably)
  • How do I read this Generics correctly from JSON?
  • JsonObject vs JSONObject
Trending Discussions on JSON-java

QUESTION

Check if JSONObject matches JSON boolean expression

Asked 2021-Mar-31 at 22:09

To explain correctly the problem I must start with an example let's say I have a list of users like this

[
    { "name": "John",  "surname": "Doe",   "age": 22 },
    { "name": "Syrus", "surname": "Black", "age": 20 }
]

And I have also a JSONObject representing a condition that must be matched like this:

{
    "OR":[
        { "name": { "eq": "John"} },
        { "AND":[
            { "name": { "eq": "Syrus"} },
            { "age": { "gt": 18 } }
        ] }
    ]
}

Which should be translated in:

name = "John" OR (name = "Syrus" AND age > 18)

Now I have to make the code that given the JSONObject condition and the list of the users checks for each users if the condition is matched. At the moment this is what I have done:

import java.util.Set;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.BiConsumer;
import com.query.Queryable;
import org.json.JSONArray;
import org.json.JSONObject;

public class QueryableTreeMap<K,V extends JSONObject> extends TreeMap<K,V> implements Queryable<JSONObject,JSONObject> {

    private static final long serialVersionUID = 2586026774025401270L;

    private static boolean test(Set<Map.Entry<String, Object>> condition, JSONObject value){
        boolean isValid = true;
        Iterator<Map.Entry<String, Object>> iter = condition.iterator();
        while(iter.hasNext()){
            Map.Entry<String, Object> subcond = iter.next();
            if(subcond.getKey().equals("OR")){
                //isValid = isValid || test((Set<Map.Entry<String, Object>>) subcond.getValue(), value);
            } else if(subcond.getKey().equals("AND")){
                //isValid = isValid && test((Set<Map.Entry<String, Object>>) subcond.getValue(), value);
            } else if(subcond.getKey().equals("NOT")){
            
            } else {
                
            }
        }
        return isValid;
    }

    @Override
    public JSONObject query(JSONObject query) {
        // the set containing the conditions
        Set<Map.Entry<String, Object>> entries = query.toMap().entrySet();
        // the JSONArray with containing the records that match the condition
        JSONArray array = new JSONArray();
        // for each JSONObject inside this structure
        this.forEach(new BiConsumer<K,JSONObject>(){

            @Override
            public void accept(K key, JSONObject value) {
                // testing if the current record matches the condition
                if(test(entries, value)) array.put(value);
            }
            
        });
        // returns a JSONObject containing a JSONArray that contains the records that match the condition
        return new JSONObject(array);
    }
}

I am currently stuck in the test method which should in-fact test if the given object matches the given condition.

I don't mind changing the format of the JSON condition as long as it is a JSONObject.

At the moment i have come up with a partial solution that builds an object called Condition that represents the boolean expression inside the JSONObject (not very efficient but still a possible solution) this is obviously not working at the moment, i need help on what i should do now

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class Condition {

    private Condition left, right;
    private String boolExpr, key, value;
    private boolean not;
    private int operationType; // greater then, less then, equal to, greater or equal of, less or equal of

    public Condition(Map<String, Object> map) {
        Set<Map.Entry<String, Object>> set = map.entrySet();
        Iterator<Map.Entry<String, Object>> iterator = set.iterator();
        while(iterator.hasNext()){
            Object entry = iterator.next();
            System.out.println(entry);
            System.out.println(entry.getClass());
            if(entry instanceof Map.Entry) {
                String key = (String) ((Map.Entry) entry).getKey();
                switch(key){
                    case "AND":
                    case "OR":
                        this.boolExpr = key;
                        break;
                    case "eq":
                    case "gt":
                    case "lt":
                    case "gte":
                    case "lte":
                        this.operationType = getOperationTypeFromString(key);
                        break;
                    case "NOT":
                        this.not = true;
                        break;
                    default:
                        this.key = key;
                        break;
                }
            }
        }
    }

    public int getOperationTypeFromString(String operation) {
        switch(operation){
            case "eq":
                return 0;
            case "gt":
                return 1;
            case "lt":
                return 2;
            case "gte":
                return 3;
            case "lte":
                return 4;
            default:
                return 0;
        }
    }

}

I would prefer not to use the Condition class and just use the JSONObject instead. I am using the org.json JSON-Java parser.

ANSWER

Answered 2021-Mar-28 at 13:19

Edit: code updated to use org.json.

Below is a working implementation that handles your example.

The function that actually does the work is match, which recursively traverses the filter and applies each node to the supplied object. The function returns true if the given object satisfies the given filter.

Conceptually the match function is mapping each construct in your filter language (AND, OR, EQ, LT etc) into its Java equivalent. E.g. AND maps to Stream.allMatch, NOT maps to the Java ! operator, EQ maps to Object.equals, etc. I.e. match is defining the semantics for your filter language.

I hope the code is self-explanatory - let me know if anything is unclear.

import org.json.*;

import java.io.*;
import java.nio.file.*;
import java.util.List;
import java.util.stream.*;

import static java.util.stream.Collectors.toList;

public class Test {

    public static void main(String[] args) throws IOException {
        final List<JSONObject> jsObjs =
                stream(readJsonArray("users.json"))
                        .map(JSONObject.class::cast)
                        .collect(toList());

        final JSONObject jsFilter = readJsonObject("filter.json");

        final List<JSONObject> matches = applyFilter(jsObjs, jsFilter);

        System.out.println(matches);
    }

    private static List<JSONObject> applyFilter(List<JSONObject> jsObjs, JSONObject jsFilter) {
        return jsObjs.stream()
                .filter(jsObj -> match(jsObj, jsFilter))
                .collect(toList());
    }

    private static boolean match(JSONObject jsObj, JSONObject jsFilter) {

        final String name = getSingleKey(jsFilter);
        final Object value = jsFilter.get(name);

        switch (name) {
            case "AND":
                return stream((JSONArray)value)
                        .map(JSONObject.class::cast)
                        .allMatch(jse -> match(jsObj, jse));
            case "OR":
                return stream((JSONArray)value)
                        .map(JSONObject.class::cast)
                        .anyMatch(jse -> match(jsObj, jse));
            case "NOT":
                return !match(jsObj, (JSONObject)((JSONArray)value).get(0));
            default:
                final JSONObject jsOp = (JSONObject)value;
                final String operator = getSingleKey(jsOp);
                final Object operand = jsOp.get(operator);
                switch (operator) {
                    case "eq": return jsObj.get(name).equals(operand);
                    case "lt": return (Integer)jsObj.get(name) < (Integer)operand;
                    case "gt": return (Integer)jsObj.get(name) > (Integer)operand;
                    default: throw new IllegalArgumentException("Unexpected operator: " + operator);
                }
        }
    }

    private static JSONObject readJsonObject(String fileName) throws IOException {
        try (Reader reader = Files.newBufferedReader(Paths.get(fileName))) {
            return new JSONObject(new JSONTokener(reader));
        }
    }

    private static JSONArray readJsonArray(String fileName) throws IOException {
        try (Reader reader = Files.newBufferedReader(Paths.get(fileName))) {
            return new JSONArray(new JSONTokener(reader));
        }
    }

    private static Stream<Object> stream(JSONArray jsa) {
        return StreamSupport.stream(jsa.spliterator(), false);
    }

    private static String getSingleKey(JSONObject jso) {
        if (jso.length() != 1) {
            throw new IllegalArgumentException("Expected single entry");
        } else {
            return jso.keySet().iterator().next();
        }
    }
}

Source https://stackoverflow.com/questions/66781122

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install JSON-java

The org.json package can be built from the command line, Maven, and Gradle. The unit tests can be executed from Maven, Gradle, or individually in an IDE e.g. Eclipse.

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Consider Popular JSON Processing Libraries
Compare JSON Processing Libraries with Highest Support
Compare JSON Processing Libraries with Permissive License
Compare JSON Processing Libraries with Highest Reuse
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.