将 InputStream 转换为 JSONObject

Posted

技术标签:

【中文标题】将 InputStream 转换为 JSONObject【英文标题】:Convert InputStream to JSONObject 【发布时间】:2014-04-23 02:08:09 【问题描述】:

我正在使用以下代码。我的问题是,有什么简单的方法可以。不做 InputStream -> BufferedReader -> StringBuilder -> 循环 -> JSONObject.toString()。

    InputStream inputStreamObject = PositionKeeperRequestTest.class.getResourceAsStream(jsonFileName);
    BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStreamObject, "UTF-8"));
    StringBuilder responseStrBuilder = new StringBuilder();

    String inputStr;
    while ((inputStr = streamReader.readLine()) != null)
        responseStrBuilder.append(inputStr);

    JSONObject jsonObject = new JSONObject(responseStrBuilder.toString());

【问题讨论】:

你所拥有的一切都很好。您可以将 BufferedReader 读取提取到静态帮助方法并重新使用它。一些第 3 方库已经这样做了。 【参考方案1】:

由于您已经在使用 Google 的 Json-Simple 库,您可以像这样从 InputStream 解析 json:

InputStream inputStream = ... //Read from a file, or a HttpRequest, or whatever.
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(
      new InputStreamReader(inputStream, "UTF-8"));

【讨论】:

不知道为什么,但是这段代码抛出异常:线程“main”中的异常 java.lang.ClassCastException: class org.json.simple.JSONArray cannot be cast to class org.json.JSONObject (org .json.simple.JSONArray 和 org.json.JSONObject 位于加载程序“app”的未命名模块中)【参考方案2】:

使用 JsonReader 来解析 InputStream。请参阅 API 中的示例: http://developer.android.com/reference/android/util/JsonReader.html

【讨论】:

这应该是公认的答案...链接中的代码很简单:JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); 它(几乎)是一个仅链接的答案。在答案中包含要点会更好。【参考方案3】:

如果你不想弄乱现成的库,你可以创建一个这样的类。

public class JsonConverter 

//Your class here, or you can define it in the constructor
Class requestclass = PositionKeeperRequestTest.class;

//Filename
String jsonFileName;

//constructor
public myJson(String jsonFileName)
    this.jsonFileName = jsonFileName;



//Returns a json object from an input stream
private JSONObject getJsonObject()

    //Create input stream
    InputStream inputStreamObject = getRequestclass().getResourceAsStream(jsonFileName);

   try 
       BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStreamObject, "UTF-8"));
       StringBuilder responseStrBuilder = new StringBuilder();

       String inputStr;
       while ((inputStr = streamReader.readLine()) != null)
           responseStrBuilder.append(inputStr);

       JSONObject jsonObject = new JSONObject(responseStrBuilder.toString());

       //returns the json object
       return jsonObject;

    catch (IOException e) 
       e.printStackTrace();
    catch (JSONException e) 
       e.printStackTrace();
   

    //if something went wrong, return null
    return null;


private Class getRequestclass()
    return requestclass;


然后,你可以这样使用它:

JSONObject jObject = new JsonConverter(FILE_NAME).getJsonObject();

【讨论】:

【参考方案4】:

此代码有效

BufferedReader bR = new BufferedReader(  new InputStreamReader(inputStream));
String line = "";

StringBuilder responseStrBuilder = new StringBuilder();
while((line =  bR.readLine()) != null)

    responseStrBuilder.append(line);

inputStream.close();

JSONObject result= new JSONObject(responseStrBuilder.toString());       

【讨论】:

【参考方案5】:

你可以使用这个apihttps://code.google.com/p/google-gson/ 简单实用,

这里是如何使用https://code.google.com/p/google-gson/ Api 来解决您的问题

public class Test 
  public static void main(String... strings) throws FileNotFoundException  
    Reader reader = new FileReader(new File("<fullPath>/json.js"));
    JsonElement elem = new JsonParser().parse(reader);
    Gson gson  = new GsonBuilder().create();
   TestObject o = gson.fromJson(elem, TestObject.class);
   System.out.println(o);
  




class TestObject
  public String fName;
  public String lName;
  public String toString() 
    return fName +" "+lName;
  

json.js 文件内容:

"fName":"Mohamed",
"lName":"Ali"

【讨论】:

这不能回答问题。请说明 Gson 如何解决他们的问题。 另外,如果提问者已经使用的库提供了解决方案,请尝试将该库与该解决方案一起使用。如果没有,请表示不要做出基本上说“使用另一个库”的答案,然后发布指向该库的链接。答案需要解释他们关联的链接,而不仅仅是链接转储。【参考方案6】:

这对我有用:

JSONArray jsonarr = (JSONArray) new JSONParser().parse(new InputStreamReader(Nameofclass.class.getResourceAsStream(pathToJSONFile)));
JSONObject jsonobj = (JSONObject) new JSONParser().parse(new InputStreamReader(Nameofclass.class.getResourceAsStream(pathToJSONFile)));

【讨论】:

请为您的回答提供一些背景信息,特别是它在做什么,以及它为什么能解决问题。【参考方案7】:

简单的解决方案:

JsonElement element = new JsonParser().parse(new InputStreamReader(inputStream));
JSONObject jsonObject = new JSONObject(element.getAsJsonObject().toString());

【讨论】:

JsonParser 不可用【参考方案8】:

我认为最好的解决方案是将 InputStream 封装在 JSONTokener 对象中。 像这样的:

JSONObject jsonObject = new JSONObject(new JSONTokener(inputStream));

【讨论】:

什么意思?要使用 JSONTokener,您必须添加 java-json 依赖项(对于 JSONObject 也是如此,这是本问题的主题......) Android框架自带的JSONTokener的构造函数不带InputStream。仅限String【参考方案9】:

利用 Jackson JSON Parser

ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(inputStreamObject,Map.class);

如果你特别想要一个 JSONObject,那么你可以转换地图

JSONObject json = new JSONObject(map);

JSONObject构造函数http://stleary.github.io/JSON-java/index.html的用法参考这里

【讨论】:

【参考方案10】:

你可以使用实体:

FileEntity entity = new FileEntity(jsonFile, "application/json");
String jsonString = EntityUtils.toString(entity)

【讨论】:

FileEntity 是否需要 FileURLInputStream?他们似乎从类路径中获取了InputStream 一个文件和内容类型。 “他们似乎从类路径中获取 InputStream”是什么意思? @SotiriosDelimanolis 他们正在使用Class#getResourceAsStream(),它为类路径上的资源返回InputStream。他们这里没有File【参考方案11】:

另一种解决方案:使用flexjson.jar:http://mvnrepository.com/artifact/net.sf.flexjson/flexjson/3.2

List<yourEntity> yourEntityList = deserializer.deserialize(new InputStreamReader(input));

【讨论】:

这不能回答问题。请说明这些库如何解决 OP 的问题。【参考方案12】:
InputStream inputStreamObject = PositionKeeperRequestTest.class.getResourceAsStream(jsonFileName);
JSONObject jsonObject = new JSONObject(IOUtils.toString(inputStreamObject));

【讨论】:

【参考方案13】:

这是一个不使用循环且仅使用 Android API 的解决方案:

InputStream inputStreamObject = PositionKeeperRequestTest.class.getResourceAsStream(jsonFileName);
byte[] data = new byte[inputStreamObject.available()];
if(inputStreamObject.read(data) == data.length) 
    JSONObject jsonObject = new JSONObject(new String(data));

【讨论】:

获取字符串:BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); String targetLcl=response.toString();【参考方案14】:

你可以按照here的建议使用这个漂亮的方法:

JSONObject getJsonFromInStream(InputStream inputStream ) throws IOException, JSONException 
    BufferedReader bR = new BufferedReader(  new InputStreamReader(inputStream));
    String line = "";

    StringBuilder responseStrBuilder = new StringBuilder();
    while((line =  bR.readLine()) != null)

        responseStrBuilder.append(line);
    
    inputStream.close();

    return new JSONObject(responseStrBuilder.toString());

【讨论】:

以上是关于将 InputStream 转换为 JSONObject的主要内容,如果未能解决你的问题,请参考以下文章

如何将 byte[] 转换为 InputStream? [复制]

将 InputStream 转换为 base64 字符串

将 inputStream 转换为 FileInputStream?

将文件和数据转换为 outputStream 并将 inputStream 转换为文件和数据

如何将 InputStream 转换为 DataHandler?

如何将 Reader 转换为 InputStream 并将 Writer 转换为 OutputStream?