Android - Save JSON from InputStream into String - java

I'm trying to parse this JSON I get from a HttpURLConnection in Android.
{
"responsejson":
{
"value1": [
{
"data": "Call",
"label": "Call",
"default": false
},
{
"data": "Email",
"label": "Email",
"default": false
}
],
"value2": [
{
"attributes": {
"type": "Status",
"url": "/..."
},
"IsOpened": false,
"IsDefault": true,
"TechLabel": "NotStarted",
"Id": "01Jb"
},
{
"attributes": {
"type": "Status",
"url": "/..."
},
"IsOpened": false,
"IsDefault": false,
"TechLabel": "InProgress",
"Id": "01Jb"
},
{
"attributes": {
"type": "Status",
"url": "/..."
},
"IsOpened": true,
"IsDefault": false,
"TechLabel": "Completed",
"Id": "01Jb"
}
],
...
}
}
What I want to do is save the content of value1 in a string, the content of value2 in another string,... because I need to store it in the database, so in the future I can load and parse it. I am using JsonReader but it's not possible to do this with JsonReader.
// ...
inputStream = conn.getInputStream();
JsonReader json = new JsonReader(new InputStreamReader(in));
json.beginObject();
while (json.hasNext()) {
String valueName = json.nextName();
// String content = ?????
}
json.endObject();
// ...
Any ideas? Custom objects are not possible due to we never know which values the JSON is going to show.

Use this to convert JSON array to string
private String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the
* BufferedReader return null which means there's no more data to
* read. Each line will appended to a StringBuilder and returned as
* String.
*/
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

Use Gson to parse the JSON that you receive in InputStream. Then you can get the ArrayList from that parsed object. Again, use Gson to serialize the arraylist back to JSON.

This code works for your example json.
public class Value1 {
public String data,label;
#SerializedName("default")
public boolean isdefault;
}
public class Value2 {
public Attributes attributes;
public boolean IsOpened,IsDefault;
public String TechLabel,Id;
}
public class Attributes {
public String type,url;
}
String jsonString = "{\"responsejson\":{\"value1\":[{\"data\":\"Call\",\"label\":\"Call\",\"default\":false},{\"data\":\"Email\",\"label\":\"Email\",\"default\":false}],\"value2\":[{\"attributes\":{\"type\":\"Status\",\"url\":\"/...\"},\"IsOpened\":false,\"IsDefault\":true,\"TechLabel\":\"NotStarted\",\"Id\":\"01Jb\"},{\"attributes\":{\"type\":\"Status\",\"url\":\"/...\"},\"IsOpened\":false,\"IsDefault\":false,\"TechLabel\":\"InProgress\",\"Id\":\"01Jb\"},{\"attributes\":{\"type\":\"Status\",\"url\":\"/...\"},\"IsOpened\":true,\"IsDefault\":false,\"TechLabel\":\"Completed\",\"Id\":\"01Jb\"}]}}";
try {
org.json.JSONObject object = new JSONObject(jsonString);
jsonString = object.getString("responsejson");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(jsonString).getAsJsonObject();
List<Value1> list1 = new Gson().fromJson(obj.get("value1"), new TypeToken<List<Value1>>() {}.getType());
List<Value2> list2 = new Gson().fromJson(obj.get("value2"), new TypeToken<List<Value2>>() {}.getType());

Since you do not know json structure beforehand, your best bet is to use GSON 2.0 feature that supports default maps and lists.
Use the following code to deserialize :
Object object = new Gson().fromJson(jsonString, Object.class);
The created object is a Map (com.google.gson.internal.LinkedTreeMap) which looks like this (for the above example)
{responsejson={value1=[{data=Call, label=Call, default=false}, {data=Email, label=Email, default=false}], value2=[{attributes={type=Status, url=/...}, IsOpened=false, IsDefault=true, TechLabel=NotStarted, Id=01Jb}, {attributes={type=Status, url=/...}, IsOpened=false, IsDefault=false, TechLabel=InProgress, Id=01Jb}, {attributes={type=Status, url=/...}, IsOpened=true, IsDefault=false, TechLabel=Completed, Id=01Jb}]}}
Use the generated object, parse it and save it in your db.
You can serialize that map back to JSON using :
String json = new Gson().toJson(object);
Hope this helps you.

just read the stream regularly and save it into a regular String, then parse that String :
// to get the general object that contains all the values
JSONObject json = new JSONObject(json_readed);
JSONObject response = json.getJSONObject("responsejson");
// to get the values
List<JSONArray> all_values = new ArrayList<JSONArray>();
Iterator<?> keys = response.keys();
while( keys.hasNext() ){
String value = (String)keys.next();
if( response.get(value) instanceof JSONArray ){
all_values.add(response.getJSONArray(value));
}
}
now you have all the values(whatever what's it's name id) combined into that ArrayList called(all_values).
Note that the JSON you provided in your question is missing opening"{" and closing"}" brackets in the beginning and the ending of it.

What you need to do is, first create a JsonObject from the json string representation, at this stage no specifics are given.
JSONObject object = new JSONObject("json_here"); //catch all exceptions thrown.
Interestingly you mentioned that the structure varies, it consider that weird, i am guessing you are pulling from different api instances. What you need to do , create a pojo class mapping the api instance name to the returned json string body.
After you attained the Object of interest, consider using GSON. A Java serialization/deserialization library to convert Java Objects into JSON and back. What you then need to do is to,serialize the pojo class,into an object.Then store into the database. I recommend using realm and not SQLite.
Example serializing the class.
class JClass {
private String jType;
private String json_body;
JClass() {
// no-args constructor
}
}
JClass j = new JClass();
j.jType ="some_type";
j.json_body = "json_body_here";
Gson gson = new Gson();
String json = gson.toJson(j);
then get the json String object, and store in database of choice.

/*
* Method to parse InputStream to String JSON
* */
private String parse(InputStream in){
StringBuilder result;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
return result.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

JSONParser parser = new JSONParser();
List<String> output = new ArrayList<String>();
try {
Object obj = parser.parse(data); // data is JSON
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("value1");
JSONArray msg2 = (JSONArray) jsonObject.get("value2");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
output.add(iterator.next());
}
String[] stringArray = output.toArray(new String[0]);
return stringArray;
} catch (Exception e) {
return null;
}

Related

Getting a JSON Object from a JSON Array isn't working

I am trying to get JSON data from a JSON array which looks like this:
{
"common": [
{
"food_name": "eggs",
"serving_unit": "large",
"tag_name": "raw eggs",
"serving_qty": 1,
"common_type": null,
"tag_id": "775",
"photo": {
"thumb": "https://d2xdmhkmkbyw75.cloudfront.net/775_thumb.jpg"
},
"locale": "en_US"
},
Here's what I am using:
public class GetDietData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
String calories = "UNDEFINED";
try {
URL urlForGetRequest = new URL("https://trackapi.nutritionix.com/v2/search/instant?query=egg");
HttpURLConnection connection = (HttpURLConnection) urlForGetRequest.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("x-app-key", "REMOVED");
connection.addRequestProperty("x-app-id", "REMOVED");
InputStream stream = new BufferedInputStream(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject jsonRes = new JSONObject();
JSONArray common = jsonRes.getJSONArray("common");
for (int i=0; i<common.length(); i++)
{
JSONObject jsonObj = common.getJSONObject(i);
calories = jsonObj.getString("food_name");
}
connection.disconnect();
} catch (IOException | JSONException e) {
editText=(findViewById(R.id.editTextDiet));
e.printStackTrace();
}
return calories;
}
#Override
protected void onPostExecute(String calories) {
if (calories == "UNDEFINED") {
Toast.makeText(Diet.this, "Food not found", Toast.LENGTH_LONG).show();
} else {
editText=(findViewById(R.id.editTextDiet));
editText.setText(calories);
}
}
}
I have the following problem:
W/System.err: org.json.JSONException: No value for common
at org.json.JSONObject.get(JSONObject.java:392)
So the problem seems to be that the "common" array has no value, hence it cannot find it's length? I'm unsure as to why it cannot see the "common" array as i have looked at numerous other questions about getting Objects from Arrays and I have replicated the code identically each time but with the same result. If I use solely a JSONObject and ignore the full array I can see in the stacktrace that it is attempting to download the whole array into that object which means it's definitely not something wrong with the GET request or the API keys.
Thanks.
the error you are getting is because you aren't passing the String response to jsonObject so it can't find any thing in an empty object
the fix is
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject jsonRes = new JSONObject(inputString); \\this is the fix
JSONArray common = jsonRes.getJSONArray("common");

Parsing arrays in Json using Gson

Parsing arrays in json using Gson.
I have this following json and trying to parse it.
{
"success": true,
"message": "success message",
"data": [
{
"city": "cityname",
"state": "statename",
"pin": 0,
"name" :{
"firstname" : "user"
},
"id" :"emailid"
}],
"status" : "done"
}
So, I have created pojo classes using http://www.jsonschema2pojo.org/
Now, I want to parse the array, for value "city".This is how I did but not sure what is wrong here.
Gson gson = new Gson();
Records obj = gson.fromJson(response,Records.class);
try {
JSONArray jsonArray = new JSONArray(obj.getData());
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String city = object.getString("city");
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(city);
dialog.show();
}}
catch (Exception e) {
e.printStackTrace();
}
And this is what getData() is defined in model class:
public class Records {
//////
private ArrayList<Datum> data = null;
public ArrayList<Datum> getData() {
return data;
}
this is not required:
try {
JSONArray jsonArray = new JSONArray(obj.getData());
...
}
catch
...
you just need to do
Records obj = gson.fromJson(response,Records.class);
and then
obj.getData();
would be great if you check that getData() is not null, beacuse something xould go wrong when deserialising
for getting the city: use the getter in the Datum class, you have at the end a list of those obejcts when you call getData
public String getCity() {
return city;
}

org.json.JSONException: JSONObject["status"] is not a JSONObject

I am now currently using a weather API from http://wiki.swarma.net/index.php?title=%E5%BD%A9%E4%BA%91%E5%A4%A9%E6%B0%94API/v2 and wished to convert the JSONObject into printable Strings. However, when I am working on the following code, two errors occurred:
public class getApi {
private static final String WEATHER_MAP_URL = "https://api.caiyunapp.com/v2/TAkhjf8d1nlSlspN/121.6544,25.1552/realtime.json";
private static final String WEATHER_TEST_API = "TAkhjf8d1nlSlspN";
public static JSONObject getWeatherJson() {
try {
URL url = new URL( WEATHER_MAP_URL );
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.addRequestProperty( "x-api-key", WEATHER_TEST_API );
BufferedReader reader = new BufferedReader(
new InputStreamReader( connection.getInputStream()) );
StringBuffer json = new StringBuffer( 1024 );
String tmp;
while( (tmp = reader.readLine()) != null )
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject( json.toString() );
if(data.getJSONObject("status").toString() != "ok" ) {
return null;
}
return data;
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
public static void main( String[] args ) {
JSONObject WeatherJson = getWeatherJson();
try {
JSONArray details = WeatherJson.getJSONObject("result").getJSONObject("hourly").
getJSONArray("skycon");
System.out.println(details.getJSONObject(0).getJSONObject("value").toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The JSONObject structure, which is also shown in the link above, is like this:
{
"status":"ok",
"lang":"zh_CN",
"server_time":1443418212,
"tzshift":28800,
"location":[
25.1552, //latitude
121.6544 //longitude
],
"unit":"metric",
"result":{
"status":"ok",
"hourly":{
"status":"ok",
"skycon":[
{
"value":"Rain",
"datetime":"2015-09-28 13:00"
},
{
...
}]
}
}
}
The error occurred:
org.json.JSONException: JSONObject["status"] is not a JSONObject.
at org.json.JSONObject.getJSONObject(JSONObject.java:557)
at getApi.getWeatherJson(getApi.java:34)
at getApi.main(getApi.java:45)
Exception in thread "main" java.lang.NullPointerException
at getApi.main(getApi.java:47)
I have looked at similar posts on the topic is not a JSONObject Exception but found that none of them can help me. I suspect that something is wrong with requesting the data, so actually, getWeatherJson() returns a null object and results in the NullPointerException and JSONObjectException.
Can anyone help me with the code?
According to the getJSONObject() Javadoc, this method will throw an exception if the returned object isn't a true JSON object, which it isn't because "status" is a string. As such, try using data.getString("status").
The status field in the JSON document you have posted is not an object. In JSON, objects are enclosed in with {} brackets. The result node however, is a nested object which holds the status key/value pair. Try the following:
JSONObject data = new JSONObject(json.toString());
if(data.getJSONObject("result").get("status").toString() != "ok" ) {
return null;
}

Gson only parsing one object correctly from JSON?

I have the following JSON:
{
"Person": {
"id": "1",
"name": "sampleName"
},
"PersonCalender ": {
"start": "2017-01-25T19:00:00+0100",
"End": "2019-05-10T19:00:00+0100"
}
}
This is its corresponding Java Object (containing 2 objects):
public class PersonRequest {
private Person person;
private PersonCalender personCalender;
//getters and setters
}
Below shows how I am trying to parse the object, however only the Person object is getting correctly parsed.
Am I making a mistake or is the my JSON not valid to be parsed by into this object using Gson?
Gson Parsing:
PersonRequest personRequest = new PersonRequest();
try {
InputStream is = PersonTest.class.getResourceAsStream("/my/path/personRequest.json");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
Gson gson = new Gson();
personRequest = gson.fromJson(bufferedReader, PersonRequest.class);
} catch (Exception e) {
logger.logMessage("Exception: " + e);
}
You have two errors here. 1 - space after PersonCalender, 2- The first letter in PersonCalender should be lowercase (according to your java code)

Parsing JSON correctly in Android Studio?

Alright, totally new to Android Studio, but I've been trying to parse backpack.tf's json in Android Studio, and I'm a bit stuck.
Here is a little snippet of json I would try to parse:
{
"response": {
"success": 1,
"current_time": 1448658000,
"items": {
"A Color Similar to Slate": {
"last_updated": 1448654419,
"quantity": 48,
"value": 99
},
And the code I'm using to parse JSON is here:
String finalJSON = buffer.toString();
JSONObject parentObject = new JSONObject(finalJSON);
JSONArray parentArray = parentObject.getJSONArray("A Color Similar to Slate");
JSONObject finalObject = parentArray.getJSONObject(3);
int price = finalObject.getInt("value");
return "$" + price;
Thanks a bunch!
Try this:
You have JSON:
{"response":{
"success": 1,
"current_time": 1448658000,
"items": {
"A Color Similar to Slate": {
"last_updated": 1448654419,
"quantity": 48,
"value": 99
},
}
}
}
Code:
String finalJSON =buffer.toString();;
JSONObject parentObject = null;
try {
parentObject = new JSONObject(finalJSON);
JSONObject objectA_Color=parentObject.getJSONObject("response").getJSONObject("items").getJSONObject("A Color Similar to Slate");
int value=objectA_Color.getInt("value");
} catch (JSONException e) {
e.printStackTrace();
}
1) Create some (custom, adjusted to your needs) Model class
public class Model {
private String title;
private List<String> authors;
//getters fields, magic ...
}
2) Parse your JSON (
public static final String JSON_PATH = "/Users/dawid/Workspace/Test/test.json";
Gson gson = new Gson();
BufferedReader br = new BufferedReader(new FileReader(JSON_PATH));
Model model = gson.fromJson(br, Model.class);
OR
1) Parse it with JSON Parser
BufferedReader br = new BufferedReader(new FileReader(JSON_PATH));
JsonParser parser = new JsonParser();
JsonObject object = parser.parse(br).getAsJsonObject();
Both ways Require GSON library https://github.com/google/gson

Categories