Using Jaca JsonPath to exclude items from JSON response - java

I am using the JsonSmartJsonProvider and my JSON looks like this
{
"info": {
"clientCount": 1,
"compactorVersion": 2,
"processMonitor": {
"processList": [
{
"name": "java.exe",
"commandLine": "",
"pid": 6224
}
]
}
}
}
I'm trying to exclude "processList", but keep everything else. I've tried variations on $.info[?(# noneof ['processMonitor'])], but I always end up with "info" being empty in the response. Is it possible to use JsonPath to do this? The code that is used to do this looks like this:
DocumentContext document = JsonPath.using(CONFIGURATION).parse(json);
Map<String, Object> result = new HashMap<>();
paths.forEach((key, value) -> result.put(key, document.read(value)));
return result;

As mentioned, you are actually looking for a JSON transformation. JOLT is a common library to do just that. A solution can look like this:
import java.util.List;
import com.bazaarvoice.jolt.Chainr;
import com.bazaarvoice.jolt.JsonUtils;
public class MyJsonTransformer {
public static void main(String[] args) throws Exception {
List<Object> specs = JsonUtils.classpathToList("/spec.json");
Chainr chainr = Chainr.fromSpec(specs);
Object inputJSON = JsonUtils.classpathToObject("/input.json");
Object transformedOutput = chainr.transform(inputJSON);
System.out.println(JsonUtils.toPrettyJsonString(transformedOutput));
}
}
And a jolt remover spec file like this:
[
{
"operation": "remove",
"spec": {
"info": {
"processMonitor": {
"processList": ""
}
}
}
}
]
You can try JOLT online with your input and the spec above here. Pretty neat.
The JSON and spec can be defined inline as well. I have not tested this end to end.

Related

Reading JSON file list returns null (can not read file)

I'm trying to read a file that contains a json object but it returns null.
here is my json file
[
{"VersionNumber": 200,
"TitleFA": "TitleFA2",
"DescriptionFA": "DescriptionFA2",
"TitleEN": "TitleEN2",
"DescriptionEN": "DescriptionEN2",
"Priority": 1 },
{"VersionNumber": 100,
"TitleFA": "TitleFA1",
"DescriptionFA": "DescriptionFA1",
"TitleEN": "TitleEN1",
"DescriptionEN": "DescriptionEN1",
"Image": "Image1",
"Priority": 1 }
]
Here is the Class that I'm trying to map it to
#JsonIgnoreProperties(ignoreUnknown = true)
public class OnBoardingItemsModel {
public int VersionNumber;
public String TitleFA;
public String DescriptionFA;
public String TitleEN;
public String DescriptionEN;
public String Image;
public int Priority; }
Here is the code I'm using it my fragment to read the file. Also my json file is in the same directory as my fragment class
private List<OnBoardingItemsModel> mOnBoardingItems;
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
try {
mOnBoardingItems = Arrays.asList(mapper.readValue(new File("OnBoardingItems.json"), OnBoardingItemsModel[].class));
} catch (IOException e) {
e.printStackTrace();
}
I tried different ways but mOnBoardingItems is always null in the end. I also tries this code and it didn't work: Java Android – Read JSON file from assets using Gson
Edit: I tried this and it returned false. I don't know why it's unable to read the file
File file = new File("OnBoardingItems.json");
Log.v("canreadfile", String.valueOf(file.canRead()));
Log.v("isfileee", String.valueOf(file.isFile()));
I have no idea what else I should check I would appreciate it if someone could help

is it possible use multi type in Class

I need to response a tree structure by json,
in my object,
{
MyClass 1:[{MyClass 11},{MyClass 12}],
MyClass 2:[{MyClass 21},{MyClass 22}],
MyClass 3:[{MyClass 31},{MyClass 32},
{MyClass 33 :[{MyClass 331},{MyClass 332}]}
]
}
I used a HashMap<MyClass, ArrayList<Object>> to do this
and it worked, but when I trans to Json by Gson().toJson
it show {MyClass Format: object Format}
like this
{
"{Id=1, Name=HQS, parentId=0, level=1}":[
{
"_Id":5,
"_Name":"ADM",
"_originalName":"ADM",
"_parentId":1,
"_originalParentId":1,
"_setOriginalParentId":false,
"_level":2,
"_originalLevel":2,
"_setOriginalLevel":false,
"_columnBitmask":0,
"_cachedModel":false,
"_new":false
},
{
"{Id=2, Name=HQS, parentId=1, level=2}":[
{
"_Id":21,
"_Name":"ADMS",
"_originalName":"ADMS",
"_parentId":2,
"_originalParentId":2,
"_setOriginalParentId":false,
"_level":3,
"_originalLevel":3,
"_setOriginalLevel":false,
"_columnBitmask":0,
"_cachedModel":false,
"_new":false
}
]
}
]
}
I guess the point is Object, how could I fix it to show my class format?

Is it possible to get variable from Java class to a html file

I'd like to use the swaggerjson String, to define as a var in a html file.
private static BeanConfig beanConfig = new BeanConfig();
public EtelApplication() {
printPath();
beanConfig.setTitle("jim-rest");
beanConfig.setResourcePackage("com.mast.api");
beanConfig.setScan(true);
beanConfig.scanAndRead();
printSwaggerJson();
createSwaggerJsonFile();
}
private void printSwaggerJson() {
String swaggerjson = Json.pretty(beanConfig.getSwagger());
System.out.println(swaggerjson);
}
My html file has this script, where I would like to use the string
window.onload = function () {
const ui = SwaggerUIBundle({name */
url: "swagger.json", name: "jim-rest",
dom_id: '#swagger-ui',
validatorUrl: null,
deepLinking: true,
spec: swaggerjson, //this is where I would like to use the var.
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
window.ui = ui
}
is it possible to use swaggerjson directly like this?
I aplogise for the very simple question, I wasn't able to find a detailed answer when searching

how to implement $size in spring Data Aggregation in java

how to implement below code in java using spring Data mongodb
db.profil.aggregate([
{ "$match": { "typ": "Organisation" } },
{ "$group": {
"_id": null,
"count": {
"$sum": { "$size": "$foos" }
}
} }
])
MongoDB has an Aggregation framework for Java to support all aggregation APIs.
Try following:
import static com.mongodb.client.model.Accumulators.*;
import static com.mongodb.client.model.Aggregates.*;
import static com.mongodb.client.model.Projections.*;
Bson match = match(eq("typ", "Organisation")));
Bson projection = new Document("$size", "$foos" );
Bson group = group("$_id", Accumulators.sum("count",projection));
MongoCursor<Document> cursor = collection.aggregate(asList(match, group)).iterator();

Why is the JSON not written?

This is code:
public static void init() {
File file = new File(SimpleMessagesAPI.getMainAPI().getDataFolder(), "config.json");
try {
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
ObjectNode firstObjectNode = objectMapper.createObjectNode();
ObjectNode secondObjectNode = objectMapper.createObjectNode();
firstObjectNode.put("period", 5);
firstObjectNode.put("async", true);
firstObjectNode.put("country", "Europe/Bucharest");
secondObjectNode.putArray("broadcast")
.add("&7Hello players! Now is %server_online players!")
.add("&eNow is %time")
.add("&6Thanks for playing on that server!")
.add("&cHave fun guys! %motd");
ArrayNode firstArrayNode = objectMapper.createArrayNode();
firstArrayNode.add(firstObjectNode);
ArrayNode secondArrayNode = objectMapper.createArrayNode();
secondArrayNode.add(secondObjectNode);
ObjectNode principalObjectNode = objectMapper.createObjectNode();
principalObjectNode.putPOJO("mechanic", firstArrayNode);
ObjectNode secondarObjectNode = objectMapper.createObjectNode();
secondarObjectNode.putPOJO("messages", secondArrayNode);
arrayNode.add(principalObjectNode);
arrayNode.add(secondarObjectNode);
if (!file.exists()) {
file.createNewFile();
objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(arrayNode);
}
/*String json = file.toString();
JsonNode jsonNode = objectMapper.readTree(json);
String messages = jsonNode.get("messages").asText();
String mechanic = jsonNode.get("mechanic").asText();
System.out.println("Messages: " + messages + "\n\n\n" + "Mechanic: " + mechanic + "\n\n");*/
//ObjectConfig config = new ObjectConfig(messages, mechanic);
//objectMapper.writeValue(new File(SimpleMessagesAPI.getMainAPI().getDataFolder() + "config.json"), config);
} catch (IOException e) {
e.printStackTrace();
}
}
And this is JSON what I want to create:
{
"mechanic": {
"period" : 5,
"async" : true,
"country" : "Europe/Bucharest"
},
"messages": {
"broadcast" : [
"&7Hello players! Now is %server_online players!",
"&eNow is %time",
"&6Thanks for playing on that server!",
"&cHave fun guys! %motd"
]
}
}
But when I executed the code, this created an empty JSON object, why?
And file.createNewFile(); says "result is ignored".
Thanks so much for help guys
There are 2 issues with your code lines
file.createNewFile();
objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(arrayNode);
You got a compiler warning on file.createNewFile(); saying
result is ignored, because you ignored the boolean result returned by
file.createNewFile().
You better should do something like this:
if (!file.createNewFile())
throw new IOException("could not create file " + file);
Your method call .writeValueAsString(arrayNode) just
produces a JSON string, but it doesn't write this string to anywhere.
You need to use .writeValue(file, arrayNode) instead.
I can suggest you a simpler way of creating json from structured data. You can create three class which represents your json structure. And you can simply initialize instance of objects and serialize it with ObjectMapper.
Here an alternative way :
package yourPackage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import java.util.Arrays;
import java.util.List;
public class Test {
public String serializeData() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
MyJson json = new MyJson();
Mechanic mechanic = new Mechanic();
mechanic.setAsync(true);
mechanic.setCountry("Europe/Bucharest");
mechanic.setPeriod(5);
Message message = new Message();
List<String> messages = Arrays.asList(
"&7Hello players! Now is %server_online players!",
"&eNow is %time",
"&6Thanks for playing on that server!",
"&cHave fun guys! %motd");
message.setBroadcast(messages);
json.setMechanic(mechanic);
json.setMessages(message);
return mapper.writeValueAsString(json);
}
}
#Data // comes from lombok
class MyJson {
private Mechanic mechanic;
private Message messages;
}
#Data
class Mechanic{
private int period;
private boolean async;
private String country;
}
#Data
class Message {
private List<String> broadcast;
}
Serialized output:
{
"mechanic": {
"period": 5,
"async": true,
"country": "Europe/Bucharest"
},
"messages": {
"broadcast": [
"&7Hello players! Now is %server_online players!",
"&eNow is %time",
"&6Thanks for playing on that server!",
"&cHave fun guys! %motd"
]
}
}
You can write to destionation file with the following line :
Files.write(Paths.get("config.json"), serializeData().getBytes());
Maven for lombok:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>

Categories

Resources