Retrieving a Json String using the correct library - java

I'm trying to get the content of msg which is ERROR. I'm doing that by transforming string return into an array.
Now the solution 1, works perfectly fine using import org.json.JSONArray;:
Vector<ClsReturn> ret = null;
ret = ds.ind(coll,uri );
JSONArray array = new JSONArray(" [{\"type\":1, \"txt\":\"ERROR\"}]");
int i = 0;
JSONObject myJsonObject = new JSONObject();
while(i < array.length()){
myJsonObject = array.getJSONObject(i);
System.out.println(myJsonObject.getString("txt"));
i++;
}
The above solution allows me tro retrieve the content of "txt", which is "ERROR".
However (below code) when I try to use the reutrn of String jsReturn = JSONArray.toJSONString(ret); I'm not capable to do that because the library I'm using doesn't support JSONArray.toJSONString, so I need to import org.json.simple.JSONArray; which in turn doesn't allow me to use array.getJSONObject(i) but both libraries org.json.simple.JSONArray and
org.json.JSONArray don't work together. Any workaround to get the desired outcome?
Vector<ClsReturn> ret = null;
ret = ds.ind(coll,uri );
String jsReturn = JSONArray.toJSONString(ret);//output(using simple.JSONArray) --> [{"type":1, "msg":"ERROR"}]
JSONArray array = new JSONArray(jsReturn);
int i = 0;
JSONObject myJsonObject = new JSONObject();
while(i < array.length()){
myJsonObject = array.getJSONObject(i);
System.out.println(myJsonObject.getString("txt"));
i++;
}

org.json.JSONArray has a toString() method that will output a JSON string. It also allows for indentation by using toString(int indent_factor)

Related

Convert JSON String to Arraylist for Spinner

I got my JSON string from my server which contains this values:
{"server_response":[{"violation":"Driving with No Helmet"},{"violation":"Try"}]}
What I'm trying to do is convert this JSON string into String Array or Arraylist
with the values of Driving with no Helmet and Try and use it as options on an Autocomplete Textview. But I cant seem to convert them correctly. Any help or tips on what I should do? Currently I am getting the JSON String from another activity and passing it to the activity where it should be used using this:
String json_string2 = getIntent().getExtras().getString("json_data");
Anyone has time I'm willing to learn. :) Thanks
PS: Managed to get it working. #Suhafer's answer is perfect. Thanks to everyone for the warm help! :)
I think first, you need to parse the json to get the list of string that you want:
String json_string2 = getIntent().getExtras().getString("json_data");
List<String> lStringList = new ArrayList<>();
try {
JSONObject lJSONObject = new JSONObject(json_string2);
JSONArray lJSONArray = lJSONObject.getJSONArray("server_response");
for (int i = 0; i < lJSONArray.length(); i++)
{
lStringList.add(
lJSONArray.getJSONObject(i).getString("violation"));
}
}
catch(Exception e)
{
e.printStackTrace();
}
Then, you need to set that list to your adapter:
ArrayAdapter<String> yourListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lStringList);
Next, implement the adapter to your AutoCompleteTextView.
lAutoCompleteTextView.setAdapter(lStringArrayAdapter);
Hope, that helps you.
Reading your comment I think you want this list to populate on an AutoCompleteTextView. I have written thoroughly what to do this will surely help If you follow these steps carefully.
First get the response and convert it to List<String> list = new ArrayList<>() format, Create a ArrayAdapter of this list by
yourListAdapter = new ArrayAdapter<String>(YourActivity.this,
android.R.layout.simple_list_item_1, list);
After this set your yourAutoCompleteTextBoxName.setAdapter(yourListAdapter);
In your Activity initialize this:
yourAutoCompleteTextBoxName.setOnEditorActionList(...){...}
also if you want your list to be clicked from AutoComplete TextView then do this:
yourAutoCompleteTextBoxName.setOnItemClickListener(...){...}
You can do this as below by using jettinson.jar
try {
String data = "{\"server_response\":[{\"violation\":\"Driving with No Helmet\"},{\"violation\":\"Try\"}]}";
JSONObject jsonObject = new JSONObject(data);
JSONArray temp = jsonObject.getJSONArray("server_response");
int length = temp.length();
if (length > 0) {
String[] recipients = new String[length];
for (int i = 0; i < length; i++) {
JSONObject nObject = new JSONObject(temp.getString(i));
recipients[i] = nObject.getString("violation");
}
}
} catch (JSONException ex) {
Logger.getLogger(JavaApplication2.class.getName()).log(Level.SEVERE, null, ex);
}
For getting your list of strings:
You can use Jackson's ObjectMapper class.
public class Data {
String violation;
...
}
List<Data> violations = objectMapper.readValue(json, new TypeReference<List<Data>>(){});
Below: "array" will have all the violations. (You will require some try / catch to surround with). Have a good day!
JSONObject json = new JSONObject(json_string2);
JSONArray violations = json.getJSONArray("server_response");
String[] array = new String[violations.length()];
for(int i = 0; i < violations.length(); i++) {
JSONObject violation = new JSONObject(violations.getString(i));
array[i] = violation.getString("violation");
}
You can use Gson library https://github.com/google/gson
Generate Plain Old Java Objects from JSON or JSON-Schema http://www.jsonschema2pojo.org/
YourJsonData jsonObject;
String json_string2 = getIntent().getExtras().getString("json_data");
Gson gson = new Gson();
jsonObject = gson.fromJson(json_string2, YourJsonData.class);
from jsonObject you can get your list i.e server_response array list.

Can't parse some JSON into a JsonArray using GSON

I am trying to get the values from a JSON response. I got everything to work, except extracting an array from the following string:
{"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}
I know GSON is trying to parse it because I get this error:
Exception in thread "main" java.lang.IllegalStateException: Not a JSON Array: {"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}
I am using the following code to attempt to parse it:
final JsonElement midElement = obj.get("mid");
final JsonArray midArray = midElement.getAsJsonArray();
for(Object rate : midArray){
final JsonObject rateObj = (JsonObject)rate;
final JsonElement openElement = rateObj.get("o");
open = openElement.getAsFloat();
final JsonElement highElement = rateObj.get("h");
high = highElement.getAsFloat();
final JsonElement lowElement = rateObj.get("l");
low = lowElement.getAsFloat();
final JsonElement closeElement = rateObj.get("c");
close = closeElement.getAsFloat();
}
First of all it doesn't look like a valid JSON array. It should look like this
[{"o":"1.18988","h":"1.18993","l":"1.18963","c":"1.18993"}]
Try this following code to parse it in JSON format.
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("mid");
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getString("o");
}
Then convert it your preferred data form.

What should i use to store multiple images?

What should i use to store multiple images that i retrieve from for loop? array or list? Is there any example functions that i can use? Below is my example for loop where i get my data.
JSONObject mainObject = new JSONObject(response.toString());
JSONArray uniObject = mainObject.getJSONArray("result");
for(int i = 0; i < uniObject.length(); i++) {
JSONObject rowObject = uniObject.getJSONObject(i);
co.img1 = ipAddress +"img/store/" + rowObject.getString("store_banner");
}
Use ArrayList<>(); It's away more flexible than the normal array;

How to decode in java a json representation of Google appengine Text

I have two appengine applications and am serving a string representation of a JSONObject from one and picking it up in the other. Every thing works well if I don't include a Text object in the JSON
Here is the specific part of the JSON object causing the trouble:
,\"text\":\u003cText: rthBlog 1\r\n\"If you don\u0027t learn from history you are doomed to repeat i...\u003e,
Here is how it looks like in string form:
< Text: rthBlog 1
"If you don't learn from history you are doomed to repeat i...>
Here are the relevant code placing the string in the data store [I am using json.simple]:
Text item_text = new Text("default text"); //it get filled by text longer than 500 char's
JSONObject j = new JSONObject();
j.put("text", item_text);
j.put("item_links", j_links);
item.setProperty("as_json", j.toJSONString());
datastore.put(item);
Here is the code retrieving it wrapping it in a JSONArray the array in a JSONobject and producing a String [I am using appengine json]:
JSONArray search_results = new JSONArray();
for(Entity e: items)
{
String j = (String) e.getProperty("as_json");
JSONObject jo;
if(j != null)
{
System.out.println(TAG + ".searchItems() string as json: " + j);
jo = new JSONObject();
jo.put("item", j);
search_results.add(jo);
}
}
JSONObject jo = new JSONObject();
jo.put("items", search_results);
return jo.toJSONString();
Here is the code picking it up [I am using appengine json]:
try
{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = (JSONArray) jsonObject.get("items");
JSONObject array_member = null;
JSONObject j;
for(int i=0; i<jsonArray.length(); i++)
{
array_member = jsonArray.getJSONObject(i);
System.out.println("array member" + array_member);
/*Text text = (Text)array_member.get("text"); //
System.out.println(text.getValue());*/
String s_item = array_member.getString("item");
System.out.println("item in string form: " + s_item);
j = new JSONObject(s_item); //This is the exception causing line
You need to be in control of your serialization and deserialization to and from JSON ...
meaning complex object are represented as simple text or numbers.
Here you are trying to serialize a complex object which is not what it is intended for. Make sure you serialize only the value the object is holding not the entire object.
A nice and very powerfull library enabling to fully take control of the serialization/deserialization process is Jackson.

Convert JSON array[array[String]] to Java array

I have a JavaScript JSON array[array[String]] called jsonArray in my JSP1.jsp.
I am converting jsonArray to a String jsonArrayStr using JSON.stringify(jsonArray) in JSP1.jsp.
I am passing jsonArrayStr as a parameter while calling another JSP JSP2.jsp this way-
"JSP2.do?jsonArrayStr="+jsonArrayStr
In JSP2.jsp, I am doing this-
String jsonArrayStr = request.getParameter("jsonArrayStr");
Now how do I convert jsonArrayStr to Java array (JSP2.jsp doesn't contain any JavaScript code)
Summary-
I have a JavaScript JSON Array in a JSP1.jsp, which I want to access as a normal Java array/arraylist in JSP2.jsp. How do I achieve this?
OK, so you have a two-dimensional array of strings represented as a JSON like this stored in a Java String:
[["a", "b", "c"],["x"],["y","z"]]
You need to somehow parse or "deserialize" that value into a Java String[][]. You can use a library like from http://www.json.org/java/index.html or http://jackson.codehaus.org/ or you can try to do it manually. Manually could be a little tricky but not impossible. The json.org library is very simple and might be good enough. The code would be something like this (I haven't tried/tested this):
JSONArray jsonArray = new JSONArray(jsonArrayStr); // JSONArray is from the json.org library
String[][] arrayOfArrays = new String[jsonArray.length()][];
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray innerJsonArray = (JSONArray) jsonArray.get(i);
String[] stringArray = new String[innerJsonArray.length()];
for (int j = 0; j < innerJsonArray.length(); j++) {
stringArray[j] = innerJsonArray.get(j);
}
arrayOfArrays[i] = stringArray;
}
somethingk like this
ArrayList<String> strings= new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
list.add(jsonArray.get(i).toString());
}
}
String[] Stringarray = strings.toArray(new String[strings.size()]);

Categories

Resources