gpt4 book ai didi

java - 使用简单的json解析设备数据并在hdfs中构建逗号分隔的文件

转载 作者:行者123 更新时间:2023-12-02 21:26:14 26 4
gpt4 key购买 nike

我的问题是关于如何解析设备api的json响应。 json如下所示。

[{"name":"Device 1","label":"Switch State","value":"off"},{"name":"Device 2","label":"Switch State","value":"on"}]


public class Fubar{

public static void main(String[] args) throws Exception {
boolean a = true;
while (a) {
Configuration conf = new Configuration();
FileSystem hdfs = FileSystem.get(conf);
String fileName = "filethingy" + "-" + new Date().getTime() + ".txt";

boolean b = true;
while(b){
String connString = "url";
URL url = new URL(connString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
out.writeBytes("TimeStamp"+",");
out.writeBytes("DeviceName"+",");
out.writeBytes("DeviceLabel"+",");
out.writeBytes("DeviceStatus"+",");
out.writeBytes("\n");
while ((inputLine = in.readLine()) != null) {
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(inputLine);

String date = new java.sql.Timestamp(System.currentTimeMillis()).toString();
out.write(date.getBytes());
out.write(",".getBytes());
out.writeBytes((String) jsonObject.get("name"));
out.write(",".getBytes());
out.writeBytes((String) jsonObject.get("label"));
out.write(",".getBytes());
out.writeBytes((String) jsonObject.get("value"));
//out.write(inputLine.getBytes());
out.write("\n".getBytes());
out.hflush();
}

in.close();
Thread.sleep(30000);
out.hflush();

}
out.close();
hdfs.close();
a=false;
b=false;
}

我知道这行不通,因为我无法将JSONArray转换为JSONObject。我在弄清楚如何正确地分离JSON时遇到麻烦,尽管最终构建了一个看起来像TimeStamp,DeviceName,DeviceLabel,DeviceStatus,01012001,Device1,Switch Status,On的csv。完成后,有人会将Hive表放在数据之上。任何帮助,将不胜感激。

最佳答案

回答了我自己的问题。

while ((inputLine = in.readLine()) != null) {

JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(inputLine);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject object = (JSONObject) jsonArray.get(i);
String date = new java.sql.Timestamp(System.currentTimeMillis()).toString();
out.write(date.getBytes());
out.write(",".getBytes());
out.writeBytes((String) object.get("name"));
out.write(",".getBytes());
out.writeBytes((String) object.get("label"));
out.write(",".getBytes());
out.writeBytes(String.valueOf(object.get("value")));
//out.write(inputLine.getBytes());
out.write("\n".getBytes());
out.hflush();

}

关于java - 使用简单的json解析设备数据并在hdfs中构建逗号分隔的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35851518/

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