gpt4 book ai didi

java - 如何在不使用 moxy 而仅使用 Java SDK 的情况下解码 JSON 响应?

转载 作者:行者123 更新时间:2023-11-30 07:12:59 24 4
gpt4 key购买 nike

我见过的每个示例都使用/需要 EclipseLink/Moxy 来解码 JSON 响应对象。有没有办法仅使用 Java SDK 实现/运行时来做到这一点?

我的代码是:

URL url = new URL( uri );
HttpURLConnection connection =( HttpURLConnection ) url.openConnection();
connection.setRequestMethod( "POST" );
connection.setRequestProperty( "Accept", "application/json" );
connection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );
connection.setRequestProperty( "charset", "utf-8");
connection.setDoOutput( true );
connection.setUseCaches(false);
connection.setDoInput(true);

//Create body for request
String body = "user=joe&pass=test";
byte[] outputInBytes = body.getBytes("UTF-8");
connection.setRequestProperty( "Content-Length", Integer.toString( outputInBytes.length ));
DataOutputStream os = new DataOutputStream( connection.getOutputStream() );

//Sent request
os.write( outputInBytes );
os.close();

//Create our unmarshaller
JAXBContext jc = JAXBContext.newInstance( LoginResponse.class );
InputStream json = connection.getInputStream();
Unmarshaller unmarshaller = jc.createUnmarshaller();

//What do I do here?
//unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE,, "application/json");

//This throws an error
//LoginResponse login = ( LoginResponse ) jc.createUnmarshaller().unmarshal( json );

//So does this
LoginResponse login = ( LoginResponse ) unmarshaller.unmarshal( json );
System.out.println( login );

最佳答案

JDK没有固有的支持。您必须使用 JSON 库之一。下面效果很好。

GSON
Jackson

关于java - 如何在不使用 moxy 而仅使用 Java SDK 的情况下解码 JSON 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38877319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com