简体   繁体   English

将Json的字符串转换为JsonObject

[英]Converting String of Json to JsonObject

I have a String of Json received from a web service http get request. 我有一个从Web服务http get请求收到的Json字符串。 I would like to turn the string that I have formed into a JsonObject. 我想将已经形成的字符串转换为JsonObject。

The question has been answered perfectly. 这个问题已经完美地回答了。 Please see answer below. 请参阅下面的答案。

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.util.List;
import java.io.*;
import java.util.*;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class RetrieveData {

    public static String httpGet(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        if (conn.getResponseCode() != 200) {
            throw new IOException(conn.getResponseMessage());
        }

        // Buffer the result into a string
        BufferedReader rd = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();

        conn.disconnect();
        return sb.toString();
    }

    public static void main(String[] args) {
        try {
            String jsonString = (httpGet("http://kinseyreporter.org/API/list/reports/?tag=male%20victim&from=2012-06-02"));
            JsonObject obj = new JsonObject();

            Gson gson = new Gson();
            System.out.println(jsonString);
            List<String> list = new ArrayList<String>();
            gson.fromJson(jsonString, (Type) list);
            String json = gson.toJson(jsonString);
            System.out.println(json);
        } catch (Exception E) {
        }
    }
}

For that, you need to parse your flux json, here the code. 为此,您需要解析您的flux json,这里是代码。

 JsonObject root = (JsonObject)new JsonParser().parse(jsonString);  

int i=0;
JsonObject dataReports

//get and print each object of reports
while(root.getAsJsonObject().get("reports").getAsJsonArray().size()>i && (dataReports=root.getAsJsonObject().get("reports").getAsJsonArray().get(i).getAsJsonObject())!=null){  

    System.out.println(dataReports.toString());
    i++;
}        

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

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