简体   繁体   English

如何从 java 中的 json object 读取多个值

[英]How to read multiple values from the json object in java

I want to read the values which is there in json object example:我想读取 json object 示例中的值:

remote":{"ip":"127.0.0.1","port":35637}远程":{"ip":"127.0.0.1","端口":35637}

How can I convert this ip and port into string in java?如何将此 ip 和端口转换为 java 中的字符串?

Here's how to use the Google Gson library to extract the two scalar values from your structure:以下是如何使用 Google Gson 库从结构中提取两个标量值:

import com.google.gson.Gson;

import java.util.Map;

class Scratch {
    public static void main(String[] args) {

        // Input data structure - note the added curly braces to make the input
        // a valid JSON dictionary and the messy escaping of double quotes.  You
        // will usually read JSON from a file or have it come in from an API call,
        // so escaping like this doesn't come up a lot.
        String json = "{\"remote\":{\"ip\":\"127.0.0.1\",\"port\":35637}}";

        // Create an instance of the Gson encoder/decoder
        Gson gson = new Gson();

        // Decode the JSON to a Java data structure
        Map<String, Map<String, Object>> map = gson.fromJson(json, Map.class);

        // Extract the "remote" key to get the inner dictionary
        Map<String, Object> remote = map.get("remote");

        // Grab the two inner values.  Numbers in JSON are doubles in Java
        String ip = (String)remote.get("ip");
        double port = (double)remote.get("port");

        System.out.println(ip);
        System.out.println((int)port);
    }
}

Result:结果:

127.0.0.1
35637

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM