关于java:将InputStream转换为JSONObject

Convert InputStream to JSONObject

我正在使用以下代码将InputStream转换为JSONObject。我的问题是,有没有简单的方法可以将InputStream转换为JSONObject。不执行InputStream-> BufferedReader-> StringBuilder->循环-> JSONObject.toString()。

1
2
3
4
5
6
7
8
9
    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());


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

1
2
3
4
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"));


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


如果您不想弄乱现成的库,您可以制作一个这样的类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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;
}
}

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

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

此代码有效

1
2
3
4
5
6
7
8
9
10
11
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());

使用Jackson JSON解析器

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

如果要专门使用JSONObject,则可以转换地图

1
JSONObject json = new JSONObject(map);

有关JSONObject构造函数的用法,请参见http://stleary.github.io/JSON-java/index.html


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

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


以下是不使用循环且仅使用Android API的解决方案:

1
2
3
4
5
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));
}


简单解决方案:

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


这对我有用:

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


您可以使用此api https://code.google.com/p/google-gson/
这很简单而且非常有用,

以下是使用https://code.google.com/p/google-gson/ Api解决问题的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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文件内容:

1
2
3
{"fName":"Mohamed",
"lName":"Ali"
}


1
2
InputStream inputStreamObject = PositionKeeperRequestTest.class.getResourceAsStream(jsonFileName);
JSONObject jsonObject = new JSONObject(IOUtils.toString(inputStreamObject));

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

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


您可以使用实体:

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