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" } ]
Related
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)**);
}
I would like to convert XML to JSON.
Currently, I make this with the lib org.json :
JSONObject jso = XML.toJSONObject(xmlStr);
However, if the XML contains number fields, I would like to have only String fields in the JSONObject.
For example:
The XML file is :
<ID>3</ID>
<NAME>ApplicationName</NAME>
The org.json permits me to have:
{
"ID" : 3,
"Name" : "ApplicationName"
}
The final result has to be :
{
"ID" : "3",
"Name" : "ApplicationName"
}
I resolve mt problem by using the latest version of org.json.
There is a methode to do this :
JSONObject jso = XML.toJSONObject(xmlStr, true);
The boolean is using to keep the string fields.
Given this POJO:
public class People {
String sex;
long age;
String names;
}
The "names" property will be a json string for which I need to create nested documents for. Here is an example of an instance I need to save to Elasticsearch using Jest Client:
People people = new People();
people.setSex("Male");
people.setAge(21);
people.setNames("[{\"fname\": \"Bob\",\"lname\": \"Smith\"},[{\"fname\": \"Mike\",\"lname\": \"Johnson\"}");
Index index = new Index.Builder(people).index("indexName").type("aType").build();
jestClient.execute(index);
The result document in ES looks like:
"_source" : {
"sex" : "Male",
"age" : 21,
"names" : "[{\"fname\": \"Bob\",\"lname\": \"Smith\"},{\"fname\": \"Mike\",\"lname\": \"Johnson\"}]"
}
So it took the String names and inserted it as a literal String, which makes sense but I actually need to create documents from each name object. In other words I want it to look like this:
"_source" : {
"sex" : "Male",
"age" : 21,
"names" : [{
"fname": "Bob",
"lname": "Smith"
}, {
"fname": "Mike",
"lname": "Johnson"
}]
}
I tried adding a mapping to tell ES to treat it as "nested" but then I get a Mapper Parsing Exception saying "tried to parse field [names] as object, but found a concrete value".
I know I should be able to do this if I create an actual Name POJO object and have a list of them, but unfortunately due to requirements I am unable to do this. I have to use the string of JSON provided in the format specified above.
SOLUTION:
Thanks to Vishal Rao for pointing me in the right direction.
The solution was to change the "names" type to a JsonArray (Google GSON). Then used the Google GSON parser as such:
People people = new People();
people.setSex("Male");
people.setAge(21);
String json = "[{\"fname\": \"Bob\",\"lname\": \"Smith\"},[{\"fname\": \"Mike\",\"lname\": \"Johnson\"}"
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(json);
JsonArray jsonArray = jsonElement.getAsJsonArray();
people.setNames(jsonArray);
Index index = new Index.Builder(people).index("indexName").type("aType").build();
jestClient.execute(index);
In addition I also have a mapping that sets the names property to a nested type.
You might want to try converting your string to a JSON object first, that's probably why you're getting that error. Elasticsearch tries to parse it as an object but finds a string there instead.
Maybe do something like:
JSONObject jsonObj = new JSONObject(names);
and then using that object.
I'm getting this error when attempting to parse some JSON previously generated with Jackson. I generate the JSON like so
String ret = "";
ret = mapper.writeValueAsString(message.getPayload());
message.setPayload(ret);
Where message.getPayload() is a HashMap, in this instance containing two strings and a List of various objects. This creates the following malformed JSON
{
"user" : "john d example",
"items" : [ {
"val" : 99.5,
"id" : "phone",
"qty" : 1
}, {
"val" : 15.5,
"id" : "wine",
"qty" : 4
} ],
"address" : "123 example street"
}
Which throws an exception when examined thusly
Map<String, Object> ret = new HashMap<String, Object>();
String s = (String)message.getPayload();
ret = mapper.readValue(s, new TypeReference<Map<String, String>>(){});
How should I properly write this Map to JSON?
TypeReference<Map<String, String>> should be TypeReference<Map<String, Object>>. Jackson is attempting to parse the values as Strings rather than Lists because that is what it expects based on the TypeReference you passed in.
I would like to walk through the json file below and save the part after "coordinates".
The json file:
{"type": "FeatureCollection","features": [{"type": "Feature","properties": {},"geometry": {"type": "LineString","coordinates": [[4.354282,52.032195],[4.354087,52.032462],[4.353783,52.032962],[4.353579,52.033437],[4.353333,52.034151],[4.352991,52.03545],[4.352517,52.037002],[4.352442,52.037352],[4.352368,52.0378],[4.352336,52.038238],[4.352331,52.039962],[4.352346,52.040706]
]
}
}
]
}
I've seen code using getJSONArray() and getJSONObject() here and here. This information helped me to select (in my case) the "geometry" tree.
My code so far (test2.geojson is the json file mentioned above):
String output = new String(Files.readAllBytes(Paths
.get("C:\\Users\\****\\Desktop\\test2.geojson")));
JSONObject obj = new JSONObject(output);
JSONArray jsonArray = obj.getJSONArray("features");
System.out.println(jsonArray);
However, this only rearranges the file and appends the first part to the end of the file.
[{"geometry":{"coordinates":[[4.354282,52.032195],[4.354087,52.032462],[4.353783,52.032962],[4.353579,52.033437],[4.353333,52.034151],[4.352991,52.03545],[4.352517,52.037002],[4.352442,52.037352],[4.352368,52.0378],[4.352336,52.038238],[4.352331,52.039962],[4.352346,52.040706]],"type":"LineString"},"type":"Feature","properties":{}}]
Any solutions to get the desired output of:
[[4.354282,52.032195],[4.354087,52.032462],[4.353783,52.032962],[4.353579,52.033437],[4.353333,52.034151],[4.352991,52.03545],[4.352517,52.037002],[4.352442,52.037352],[4.352368,52.0378],[4.352336,52.038238],[4.352331,52.039962],[4.352346,52.040706]
]
}
}
]
}
Thanks in advance.
Cheers!
As "geometry" is a json object {}, "coordinates" is a json array [],
You should be doing
JSONArray jsonArray = obj.getJSONArray("features");
JSONArray resultArray = jsonArray.getJSONObject[0].getJSONObject("geometry").getJSONArray("coordinates")