This is a question related to the processing of java map.

Asked 2 years ago, Updated 2 years ago, 25 views

I am studying java while playing javascript, and I have a question about the map.
I receive an object list from the server, and I want to extract an object that corresponds to the desired key from the object value.
As an example, I want to get the result of extracting a and c out of the values a, b, and c.

Data received from server

"data": [
    {
        "a": "a-1",
        "b": "b-1",
        "c": "c-1"
    },
    {
        "a": "a-2",
        "b": "b-2",
        "c": "c-2"
    },
    {
        "a": "a-3",
        "b": "b-3",
        "c": "c-3"
    }
]

Data to be extracted

"data": [
    {
        "a": "a-1",
        "c": "c-1"
    },
    {
        "a": "a-2",
        "c": "c-2"
    },
    {
        "a": "a-3",
        "c": "c-3"
    }
]

java

2022-09-22 19:47

1 Answers

Java does not support json in the default library. You must receive a third-party library.

I'll write an example using jshell and jackson. Here, jshell used a maven-enabled version (https://github.com/kawasima/try-artifact).

json saved https://api.myjson.com/bins/xs4l6 here.

Please do the example below yourself.

-> /resolv com.fasterxml.jackson.core:jackson-databind:jar:2.9.7

-> import java.net.*
-> import com.fasterxml.jackson.databind.*
-> import com.fasterxml.jackson.databind.node.*

-> ObjectMapper mapper = new ObjectMapper()
-> JsonNode jsonNode = mapper.readTree(new URL("https://api.myjson.com/bins/xs4l6"))
-> jsonNode
|  |  Variable jsonNode of type JsonNode has value {"data":[{"a":"a-1","b":"b-1","c":"c-1"},{"a":"a-2","b":"b-2","c":"c-2"},{"a":"a-3","b":"b-3","c":"c-3"}]}

-> for(JsonNode node : jsonNode.get("data")) {
>> ((ObjectNode)node).remove("c");
>> }
-> String result = mapper.writeValueAsString(jsonNode)
|  |  Added variable result of type String with initial value "{\"data\":[{\"a\":\"a-1\",\"b\":\"b-1\"},{\"a\":\"a-2\",\"b\":\"b-2\"},{\"a\":\"a-3\",\"b\":\"b-3\"}]}"
-> System.out.println(result)
{"data":[{"a":"a-1","b":"b-1"},{"a":"a-2","b":"b-2"},{"a":"a-3","b":"b-3"}]}


2022-09-22 19:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.