简体   繁体   English

JSON 在 java 中使用 Gson 进行解析

[英]JSON Parsing in java using Gson

I am attempting to run a simple HTTP server that I will send a request to with JSON string in the body and I need to extract data from it.我正在尝试运行一个简单的 HTTP 服务器,我将使用正文中的 JSON 字符串向该服务器发送请求,我需要从中提取数据。 I'm new to Java and having a difficulty doing so.我是 Java 的新手,这样做有困难。 Ive searched online and most of the examples dont work for me, so there must be something im doing wrong.我在网上搜索过,大多数例子都不适合我,所以我一定有什么地方做错了。

public class shareManagerServer {

    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(8500), 0);
        HttpContext context = server.createContext("/shareWithUser");
        context.setHandler(shareManagerServer::handleshareWithUserRequest);
        server.start();
    }

    private static void handleshareWithUserRequest(HttpExchange exchange) throws IOException {
        if (exchange.getRequestMethod().equalsIgnoreCase("POST")) {
            Headers requestHeaders = exchange.getRequestHeaders();

            // Request body
            String body = utils.readString(exchange.getRequestBody());
    }
    }
}

Based on this, how would I get this to an object that I can access the JSON information with?基于此,我如何将其发送到可以访问 JSON 信息的 object ? For testing im sending this curl:为了测试我发送这个 curl:

curl -X POST -d "{'age':26,'email':'norman@futurestud.io','isDeveloper':true,'name':'Norman'}" localhost:8500/shareWithUser

Edit:编辑:

From my utils:从我的实用程序:

public class utils {
    public static String readString(InputStream inputStream) throws IOException {

        ByteArrayOutputStream into = new ByteArrayOutputStream();
        byte[] buf = new byte[4096];
        for (int n; 0 < (n = inputStream.read(buf));) {
            into.write(buf, 0, n);
        }
        into.close();
        return new String(into.toByteArray(), "UTF-8"); // Or whatever encoding
    }
}

First you can create class with having all the properties首先,您可以创建具有所有属性的 class

public class Person {

  private int age;
  private String email;
  private boolean isDeveloper;
  private String name;

  //getters and setters

  }

Now it is pretty string forward by using Gson现在使用Gson可以很好地实现

String body = utils.readString(exchange.getRequestBody());

Gson gson = new Gson();

Person person = gson.fromJson(body, Person.class);

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

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