Java Implementation of JsonLogic Not Working - java

Has anyone successfully used the Java implementation of JsonLogic?
This rule
{"==" : [ { "var" : "code" }, "ER"]}
gives the correct answer (true) with this data
{"code": "ER", "name": "Exploratory Research"}
using the javascript playground.
However, this Java code
JavaJsonLogic jsonLogic = JavaJsonLogic.INSTANCE;
String rule = "{\"==\" : [ { \"var\" : \"code\" }, \"ER\"]}";
JsonObject data = new JsonObject();
data.addProperty("code", "ER");
data.addProperty("name", "Exploratory Research")
System.out.println(jsonLogic.apply(rule, data)););
returns false!

JsonLogic jsonLogic = new JsonLogic();
String rule = "{\"==\" : [ { \"var\" : \"code\" }, \"ER\"]}";
//JsonObject data = new JsonObject();
Map<String, Object> data = new HashMap<>();
data.put("name", "Exploratory Research");
data.put("code", "ER");
jsonLogic.apply(rule, data);
I am using a hashmap to populate value in place of JsonObject. And the result is coming out as true. And also i am using https://mvnrepository.com/artifact/io.github.jamsesso for parsing jsonLogic string and validating the data over jsonlogic.

dmillerw too did the jsonlogic implementation for java based off of jsonlogic spec that you were following. I just tried by picking up the code base from below URL and with your test data, it is working like a charm.
https://github.com/dmillerw/json-logic-java
Here is what I had in my junit to test your need:
String testjson = **"[[{\"==\" : [ { \"var\" : \"code\" }, \"ER\"]},{\"code\": \"ER\", \"name\": \"Exploratory Research\"},true]]";**
JsonArray testArray = gson.fromJson(testjson, JsonArray.class);
for (JsonElement element : testArray) {
JsonArray array = element.getAsJsonArray();
JsonElement test = array.get(0);
JsonElement data = array.get(1);
JsonElement expected = array.get(2);
System.out.println(**JsonLogic.apply(test, data)**);
}

Related

Parse Json from Java properties file using gson library

I need to read and parse a json array from java properties file. I'm able to read the properties file and get the json array String. But I'm unable to parse the json array and get the values. I'm using gson library. Here is the data from properties file
jsonarray = [ { key1 : value1, key2 : value2 } ]
Code:
Properties properties = new Properties();
properties.load(new FileInputStream(filePath));
String jsonArray = properties.getProperty("jsonarray")
JsonElement element = new JsonPrimitive(jsonArray);
JsonArray array = element.getAsJsonArray();
I'm getting IllegalStateException
java.lang.IllegalStateException: Not a JSON Array: "[ { key1 : value1, key2 : value2 } ]"
The problem is it is taking extra double quotes at the beginning and at the end.
I have tried adding quotes to keys and values, but with no success. I need to use gson library itself, so please don't suggest other libraries. I cannot create a POJO class for it and use new Gson().fromJson(jsonArray), so kindly please don't suggest that also.
I've searched and tried a lot without success. The method I referred is given here
Thanks in advance
Edit 1: I've tried the following in properties file
jsonarray = [ { "key1" : "value1", "key2" : "value2" } ]
and I got same exception like
java.lang.IllegalStateException: Not a JSON Array: "[ { \"key1\" : \"value1\", \"key2\" : \"value2\" } ]"
I tried to create a JsonArray object in code and print it
JsonArray array = new JsonArray();
JsonObject object = new JsonObject();
object.addProperty("key1", "value1");
object.addProperty("key2", "value2");
array.add(object);
System.out.println(array.toString());
The output was as below
[{"key1":"value1","key2":"value2"}]
The Javadoc of JsonPrimitive you've used here
JsonElement element = new JsonPrimitive(jsonArray);
states
Create a primitive containing a String value.
When you then do
JsonArray array = element.getAsJsonArray();
it'll obviously fail because element is a JSON String, not a JSON array. Just parse the JSON directly
JsonArray array = new Gson().fromJson(jsonArray, JsonArray.class)
This is all after you've changed your properties file content to be actual JSON
jsonarray = [ { "key1" : "value1", "key2" : "value2" } ]

Getting a Value from a JsonArray using gson

I have searched everywhere and cannot find out how to do this, I'm super stuck. I have NO experience with JSON files, so spoon feeding is appreciated along with an explanation.
I have this JSON text here for testing:
{
"id":"4566e69fc90748ee8d71d7ba5aa00d20",
"properties":
[
{
"name":"textures",
"value":"eyJ0aW1lc3RhbXAiOjE0ODI4ODAxNDMwNzYsInByb2ZpbGVJZCI6IjQ1NjZlNjlmYzkwNzQ4ZWU4ZDcxZDdiYTVhYTAwZDIwIiwicHJvZmlsZU5hbWUiOiJUaGlua29mZGVhdGgiLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTNlODFiOWUxOWFiMWVmMTdhOTBjMGFhNGUxMDg1ZmMxM2NkNDdjZWQ1YTdhMWE0OTI4MDNiMzU2MWU0YTE1YiJ9LCJDQVBFIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjJiOWM1ZWE3NjNjODZmYzVjYWVhMzNkODJiMGZhNjVhN2MyMjhmZDMyMWJhNTQ3NjZlYTk1YTNkMGI5NzkzIn19fQ==",
},
],
"name":"Thinkofdeath",
}
I currently have this:
JsonElement playerProfile = new JsonParser().parse(jsonLine);
JsonObject jsonProfile = playerProfile.getAsJsonObject();
JsonArray properties = jsonProfile.getAsJsonArray("properties");
Which returns
[
[
{
"name":"textures",
"value":"eyJ0aW1lc3RhbXAiOjE0ODI4ODAxNDMwNzYsInByb2ZpbGVJZCI6IjQ1NjZlNjlmYzkwNzQ4ZWU4ZDcxZDdiYTVhYTAwZDIwIiwicHJvZmlsZU5hbWUiOiJUaGlua29mZGVhdGgiLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTNlODFiOWUxOWFiMWVmMTdhOTBjMGFhNGUxMDg1ZmMxM2NkNDdjZWQ1YTdhMWE0OTI4MDNiMzU2MWU0YTE1YiJ9LCJDQVBFIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjJiOWM1ZWE3NjNjODZmYzVjYWVhMzNkODJiMGZhNjVhN2MyMjhmZDMyMWJhNTQ3NjZlYTk1YTNkMGI5NzkzIn19fQ==",
},
]
Of course. How do I get the "value" from this JsonArray? Note I'm using Google's API, Gson
You can get values using:
JsonObject propertiesJson = properties.get(0);
String value = propertiesJson.getString("value");
array is JsonArray object from com.google.gson library
for (int i=0; i<array.size(); i++) {
JsonObject json = array.get(i).getAsJsonObject();
String value = json.get("key").getAsString();
}

Decoding JSON String for List with names

I am try to decode a JSON string as below
{
"id_value": [
{
"id": "1.1.1.1",
"value": "v1"
},
{
"id": "1.1.1.2",
"value": "v2"
}
]
}
Which is basically a list of id_value object. IdValue is a POJO class with a string variable of id and value.
I am able to decode the JSON string , when I passed in JSON without the list name , as below.
[
{
"id": "1.1.1.1",
"value": "v1"
},
{
"id": "1.1.1.2",
"value": "v2"
}
]
My JAVA code is as below :
String jsonString1 = "{\"id_value\": [{\"id\": \"1.1.1.1\",\"value\": \"v1\"},{\"id\": \"1.1.1.2\",\"value\": \"v2\"}]}";
String jsonString2 = "[{\"id\": \"1.1.1.1\",\"value\": \"v1\"},{\"id\": \"1.1.1.2\",\"value\": \"v2\"}]";
List<IdValue> idValues = null;
try {
Gson gson = new Gson();
idValues = gson.fromJson(jsonString2, new TypeToken<List<IdValue>>(){}.getType());
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println(idValues);
My code works well with jsonString2 , but I am getting the below exception with jsonString1. Both of them are lists , but why it is failing for one and working for other.
com.google.gson.JsonParseException: The JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter#67ac19 failed to deserialize json object {"id_value":[{"id":"1.1.1.1","value":"v1"},{"id":"1.1.1.2","value":"v2"}]} given the type java.util.List<com.something.json.IdValue>
Any inputs would be helpful.
Thanks !!
jsonString2 represents a List<IdValue>
jsonString1 represents a Map<String, List<IdValue>>
So, to process jsonString1 you need:
Map<String, List<IdValue>> map = gson.fromJson(json, new TypeToken<Map<String, List<IdValue>>>(){}.getType());
List<idValue> idValues = map.get("id_value");
Here is more general way to get your IdValues from jsonString1 even if there are another entries in it:
Gson gson = new Gson();
JsonParser parser = new JsonParser();
String jsonString1 = "{\"id_value\": [{\"id\": \"1.1.1.1\",\"value\": \"v1\"},{\"id\": \"1.1.1.2\",\"value\": \"v2\"}]}";
JsonElement e = parser.parse(jsonString1);
JsonArray idValueArray = e.getAsJsonObject().getAsJsonArray("id_value");
List<IdValue> idValues = gson.fromJson(idValueArray, new TypeToken<List<IdValue>>(){}.getType());
id_value isn't part of your IdValue POJO. So the TypeToken of List does not know how to map the id_value piece of the JSON string.
Because jsonString1's deserializing type is not same with jsonString2's. If you want to use same deserializing type, you should first do substring.
jsonString1 = jsonString1.substring(s.indexOf("["));
jsonString1 = jsonString1.substring(0, s.lastIndexOf("]") + 1);

Extracting data from JSON array

I know its an array, but I am completely new to JSON and need help comprehending how this is structured, here is my attempt at extracting data:
String JSonString = readURL("//my URL is here");
JSONArray s = JSONArray.fromObject(JSonString);
JSONObject Data =(JSONObject)(s.getJSONObject(0));
System.out.println(Data.get("name"));
My JSON data that I have goes like this :
{
"sports": [
{
"name": "basketball",
"id": 40,
"uid": "s:40",
"leagues": [
{
"name": "National Basketball Assoc.",
"abbreviation": "nba",
"id": 46,
"uid": "s:40~l:46",
"groupId": 7,
"shortName": "NBA",
"athletes": []
}
]
}
],
"resultsOffset": 10,
"resultsLimit": 10,
"resultsCount": 1,
"timestamp": "2013-11-18T03:15:43Z",
"status": "success"
}
I dont really have a strong grasp of this stuff so all the help is appreciated.
Here is the idea :
JSONObject root = new JSONObject(yourJsonString);
JSONArray sportsArray = root.getJSONArray("sports");
// now get the first element:
JSONObject firstSport = sportsArray.getJSONObject(0);
// and details of the first element
String name = firstSport.getString("name"); // basketball
int id = firstSport.getInt("id"); // 40
JSONArray leaguesArray = firstSport.getJSONArray("leagues");
// and so on, you can process leaguesArray similarly
It should work (feel free to complain about compile errors if there are any)
Your JSON data is an object (it starts with a curly brace). In the next inner layer, there is a single array (at key "sports"):
String jsonString = readURL("//my URL is here");
JSONObject result = JSONObject(jsonString);
JSONArray sports = result.getJSONArray("sports");
JSONObject sport = sport.getJSONObject(0);
System.out.println(sport.getString("name"));
I might have used another JSON library than you.
JSON means JavaScript Object Notation.
Objects in javascripts are just containers and can be represented by key-value pairs. Please find below notations to understand about json.
Represent objects in json: E.g. Student
{"name" : "Robin", "rollnumber" : "1"}
Represent array in json : E.g. Array of students
[{"name" : "Robin", "rollnumber" : "1"}, {"name" : "Mark", "rollnumber" : "2"}]
You can understand more on JSON from diagrams on this link http://www.json.org/fatfree.html
There are various ways available to to convert JSON to javaobject and javaobject to JSON : One of them is http://wiki.fasterxml.com/JacksonInFiveMinutes
Adding detailed code here along with the imports .
If this helps.
import org.json.JSONException;
import org.json.JSONObject;
public class extractingJSON {
public static void main(String[] args) throws JSONException {
// TODO Auto-generated method stub
String jsonStr = "{\"name\":\"SK\",\"arr\":{\"a\":\"1\",\"b\":\"2\"},\"arrArray\":[{\"a\":\"1\",\"b\":\"2\"}]}";
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("name");
System.out.println(name);
String first = jsonObj.getJSONObject("arr").getString("a");
System.out.println(first);
first = jsonObj.getJSONArray("arrArray").getJSONObject(0).getString("a");
System.out.println(first);
}
}

issue in looping

I am facing issue in looping in the following code,i am passing a list of forms to it,i am not sure what is going wrong,i need the output as but i am getting only the last form_id.I have this code to get this output as ,here i am passing a list of forms and getting the json as output. Please let me know where am i going wrong.
output :
{
"forms": [
{ "form_id": "1", "form_name": "test1" },
{ "form_id": "2", "form_name": "test2" }
]
}
code :
public class MyFormToJSONConverter {
public JSONObject getJsonFromMyFormObject(List<Form> form) {
JSONObject responseDetailsJson = new JSONObject();
JSONArray jsonArray = null;
List<JSONArray> list = new ArrayList<JSONArray>();
System.out.println(form.size());
for (int i = 0; i < form.size(); i++) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", form.get(i).getId());
formDetailsJson.put("form_name", form.get(i).getName());
formDetailsJson.put("desc",
form.get(i).getFormDescription());
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
list.add(jsonArray);
}
for (JSONArray json : list) {
responseDetailsJson.put("form", json);
}
return responseDetailsJson;
}
Your problem is here:
for (JSONArray json : list) {
responseDetailsJson.put("form", json);
}
will overwrite all of the previous values with the next value (a single JSON object). You want
responseDetailsJson.put("form", list);
You probably should also get rid of this:
jsonArray = new JSONArray();
jsonArray.add(formDetailsJson);
list.add(jsonArray);
That will give you:
{
"forms": [
[{ "form_id": "1", "form_name": "test1" }],
[{ "form_id": "2", "form_name": "test2" }]
]
}
All told, I think you want:
JSONObject responseDetailsJson = new JSONObject();
List<JSONObject> list = new ArrayList<JSONObject>();
System.out.println(form.size());
// List.get will be very inefficient if passed a LinkedList
// instead of an ArrayList.
for (Form formInstance:form) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("form_id", formInstance.getId());
formDetailsJson.put("form_name", formInstance.getName());
formDetailsJson.put("desc",
formInstance.getFormDescription());
list.add(formDetailsJson);
}
responseDetailsJson.put("form", list);
JSON objects are essentially key/value pairs. In your code you are doing:
for (JSONArray json : list)
{
responseDetailsJson.put("form", json);
}
You're overwriting the same key each time.

Categories

Resources