Java 将 InputStream 转换为 JSONObject

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22461663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:52:14  来源:igfitidea点击:

Convert InputStream to JSONObject

javaandroidjsoninputstream

提问by AAV

I am converting InputStream to JSONObject using following code. My question is, is there any simple way to convert InputStream to JSONObject. Without doing InputStream -> BufferedReader -> StringBuilder -> loop -> JSONObject.toString().

我正在使用以下代码将 InputStream 转换为 JSONObject。我的问题是,是否有任何简单的方法可以将 InputStream 转换为 JSONObject。不做 InputStream -> BufferedReader -> StringBuilder -> loop -> 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());

回答by Blackbelt

you could use an Entity:

你可以使用一个实体:

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

回答by elhaj

You can use this api https://code.google.com/p/google-gson/
It's simple and very useful,

你可以使用这个api https://code.google.com/p/google-gson/
很简单也很有用,

Here's how to use the https://code.google.com/p/google-gson/Api to resolve your problem

以下是如何使用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 file content :


json.js 文件内容:

{"fName":"Mohamed",
"lName":"Ali"
}

回答by mig8

Another solution: use flexjson.jar: http://mvnrepository.com/artifact/net.sf.flexjson/flexjson/3.2

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

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

回答by Arthur

If you don't want to mess with ready libraries you can just make a class like this.

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

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;
}
}

Then, you can use it like this:

然后,您可以像这样使用它:

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

回答by iftach barshem

use JsonReader in order to parse the InputStream. See example inside the API: http://developer.android.com/reference/android/util/JsonReader.html

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

回答by Sasanka Panguluri

Since you're already using Google's Json-Simplelibrary, you can parse the json from an InputStreamlike this:

由于您已经在使用 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"));

回答by Tharindu Dhanushka

This code works

此代码有效

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());       

回答by Murali

This worked for me:

这对我有用:

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

回答by Surendra Kumar

Simple Solution:

简单的解决方案:

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

回答by Daniele Zagnoni

The best solution in my opinion is to encapsulate the InputStream in a JSONTokener object. Something like this:

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

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