How to parse JSON array from file? - java

I have JSON from file.
{
"from_excel":[
{
"solution":"Fisrt",
"num":"1"
},
{
"solution":"Second",
"num":"2"
},
{
"solution":"third",
"num":"3"
},
{
"solution":"fourth",
"num":"4"
},
{
"solution":"fifth",
"num":"5"
}
]
}
and want to parse list of Solution and Num.
Used lib org.json.simple.*
Try this one
Object obj = parser.parse(new FileReader("E:\\json.txt"));
JSONObject jsonObject = (JSONObject) obj;
out.println(jsonObject.get("from_excel"));
JSONObject obj_new = (JSONObject) jsonObject.get("from_excel");
JSONArray solution = (JSONArray) obj_new.get("solution");
Iterator iterator = solution.iterator();
while (iterator.hasNext()) {
out.println(iterator.next());
}
What am I doing wrong?
If try to write
JSONObject solutions = (JSONArray) jsonObject.get("from_excel");
If try to write
JSONArray array = obj.getJSONArray("from_excel");
get error

working solution
JSONParser parser = new JSONParser();
JSONObject jsonObject;
try {
jsonObject = (JSONObject) parser.parse(new FileReader("E:\\json.txt"));
out.println("<br>"+jsonObject);
JSONArray from_excel = (JSONArray)jsonObject.get("from_excel");
// for row output 1
for(Object o: from_excel){
out.println("<br>"+o);
}
// for row output 2
Iterator iterator = from_excel.iterator();
while (iterator.hasNext()) {
out.println("<br>"+iterator.next());
}
// for item output 3
for (int i = 0; i < from_excel.size(); i++) {
JSONObject jsonObjectRow = (JSONObject) from_excel.get(i);
String num = (String) jsonObjectRow.get("num");
String solution = (String) jsonObjectRow.get("solution");
out.println("<br>num="+num+"; solution="+solution);
}
} catch (Exception e) {
out.println("Error: "+e);
}

There is no "solution" array in the JSON. "from_excel" is the array. So your code should look like this :
Object obj = parser.parse(new FileReader("E:\\json.txt"));
JSONObject jsonObject = (JSONObject) obj;
out.println(jsonObject.get("from_excel"));
JSONArray solutions = (JSONArray) jsonObject.get("from_excel");
Iterator iterator = solutions.iterator();
while (iterator.hasNext()) {
out.println(iterator.next());
}

from_excel is JSON array not an object. So you should achieve it is array.
JSONObject jsonObject = (JSONObject) obj;
JSONArray array = obj.getJSONArray("from_excel");
then iterate the array and get each jsonobject. Something like the below
for(int i = 0 ; i < array.length() ; i++){
array.getJSONObject(i).getString("solution");
}

Related

JSONObject data send to JSONArray

JSONObject data = response.getJSONObject("data");
Iterator x = data.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()){
String key = (String) x.next();
jsonArray.put(data.get(key));
}
Log.d("TZX", String.valueOf(jsonArray));
I have JSONObject on variable data like this
{"type":"DISKON","result":"DUPE","data":{"1":{"Code":"DISC2","Description":"DISC SALES","Value":0},"2":{"Code":"DISC1.5%","Description":"DISC1.5%","Value":1.5},"3":{"Code":"DISC 2%","Description":"DISC 2%","Value":2}}}
How to i get Object "Value" on JSONObject for send to JSONArray on variable "jsonArray"
Sorry for my grammar and I'm newbie
谢谢
try this,
JSONObject data = response.getJSONObject("data");
JSONArray jsonArray = new JSONArray();
Iterator<?> keys = data.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if (data.get(key) instanceof JSONObject) {
jsonArray.put(((JSONObject) data.get(key)).getString("Value"));
}
}
Log.e("TZX", String.valueOf(jsonArray));
You are having array, so use JsonArray directly to parse data as in
JSONArray array = response.getJSONArray("data");
List<Integer> values = new ArrayList<>();
for(int i=0;i < array.length();i++){
values.add(array.getJSONObject(i).getInt("Value"));
}
You variable data is not JSONObject it's JSONArray.
data = [{"Code":"DISC2","Description":"DISC SALES","Value":0},{"Code":"DISC1.5%","Description":"DISC1.5%","Value":1.5},{"Code":"DISC 2%","Description":"DISC 2%","Value":2}]
To get JSONObject from array
JSONArray list = new JSONArray();
JSONObject obj = new JSONObject(data)
JSONArray jsonArray = new JSONArray(obj);
for(int i=0;i<json.length();i++){
JSONObject e = jsonArray.getJSONObject(i);
String value = e.getString("Value"));
list.put(value);
}

Trouble extracting values from JSON object in Java

Okay, I'm struggling here. I am getting the following JSON formated string from my php server (called "result") (edited! I was missing a curly brace at the end):
{"L1":[{"UserName":"User1","Avatar":"1"},{"UserName":"User2","Avatar":"2"},{"UserName":"User3","Avatar":"3"}],"L2":[{"UserName":"User4","Avatar":"4"},{"UserName":"User5","Avatar":"5"}]}
I'm trying to extract an ArrayList with the Avatar numbers from the L1 object(?). But I get an error
org.json.JSONException: Value
[{"UserName":"User1","Avatar":"1"},{"UserName":"User2","Avatar":"2"},{"UserName":"User3","Avatar":"3"}]
at L1 of type org.json.JSONArray cannot be converted to JSONObject
Here's my code:
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = new JSONArray(jsonObject.getJSONObject("L1"));
ArrayList<Integer> arrList = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
arrList.add(json.getInt("Avatar"));
AvatarList = arrList;
}
}
String query_result = "SUCCESS";
if (query_result.equals("FAILURE")) {
} else {
setAvatars(AvatarList);
}
} catch (JSONException e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
If I use
jsonObject.getJSONArray("L1")
I get the same error.
Any suggestions?
Thanks in advance!
(edit: I made a mistake in the original post. There was a missing curly brace in the JSON string. Thanks to those who caught that)
Try the below one.Its working fine. I'm using json-simple-1.1.1 jar
String r="{\"L1\":[{\"UserName\":\"User1\",\"Avatar\":\"1\"},{\"UserName\":\"User2\",\"Avatar\":\"2\"},{\"UserName\":\"User3\",\"Avatar\":\"3\"}],\"L2\":[{\"UserName\":\"User4\",\"Avatar\":\"4\"},{\"UserName\":\"User5\",\"Avatar\":\"5\"}]}";
Object obj=JSONValue.parse(r);
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonArray = (JSONArray) jsonObject.get("L1");
ArrayList<Integer> arrList = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject json = (JSONObject) jsonArray.get(i);
arrList.add((Integer.parseInt((String) json.get("Avatar"))));
AvatarList = arrList;
}
}
String query_result = "SUCCESS";
if (query_result.equals("FAILURE")) {
} else {
setAvatars(AvatarList);
}
This ended up working for me if anyone stumbles upon this. I don't really understand why this worked and my original method didn't... something to do with JSONObjects vs JSONArrays vs Strings and things like [, {, }, and ] probably.
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = new JSONArray(jsonObject.getString("L1"));
ArrayList<Integer> arrList = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
arrList.add(json.getInt("Avatar"));
AvatarList = arrList;
}
}

Convert JSONObject to List<JSONObject> or a String to List<JSONObject>

I submit a query from my Java application, which upon running on Elasticsearch server returns the result in the form of a string. I want the result as a list of JSONObject objects. I can convert the string to a JSONObject using JSONObject jsonResponse = new JSONObject(responseString).
Is there any method by which I can get this in the form of a List<JSONObject>?
Instead of using JSONObject you may use JSONArray. If you really need to convert it to a List you may do something like:
List<JSONObject> list = new ArrayList<JSONObject>();
try {
int i;
JSONArray array = new JSONArray(string);
for (i = 0; i < array.length(); i++)
list.add(array.getJSONObject(i);
} catch (JSONException e) {
System.out.println(e.getMessage());
}
There is an answer of your question:
https://stackoverflow.com/a/17037364/1979882
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
This method is really easy and works too
try {
JSONObject jsonObject = new JSONObject(THESTRINGHERE);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonArray;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
// System.out.println(listdata);
} catch (Exception e) {
System.out.println(e.getMessage());
}

How to parse array from JsonArray?

I have JSON array like
"Headlines": [
{
"Title": "SPYRUS Announces Support for Windows To Go 10 Preview",
"Date": "2/18/2015",
"UTCOffset": 0,
"Source": "Marketwire - News Releases",
"Url": "http://www.redinews.com/news/?story=201502151176008.html",
"Images": [],
"Tags": [
{
"TagType": "Symbols",
"TagValues": [
"MSFT"
]
},
{
"TagType": "Companies",
"TagValues": [
"Microsoft Corporation"
]
},
I am accessing "Headlines" with this code using org.json.simple.parser.JSONParser
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(obj);
JSONArray lang = (JSONArray) jsonObject.get("Headlines");
System.out.println(lang);
but I need access "Tags" sub array and get TagType and TagValues
How to access it?
will be good also know how to parse sub array with org.codehaus.jackson.
Thanks
see this link.
it explains how to iterate over an json array
the code should be something like this
JSONArray headlines = (JSONArray) jsonObject.get("Headlines");
Iterator<String> iterator = headlines.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
Check this
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(obj);
JSONArray lang = (JSONArray) jsonObject.get("Headlines");
JSONArray tag = lang.getJSONArray("tag");
for (int i = 0; i < tag .length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
JSONArray temp= jsonobject .getJSONArray("TagValues");
String tagValue = temp.getString(0);
String tagType = jsonobject.getString("TagType");
}
Here is a code which really work, used simple json and org.codehaus.jackson togheter.
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(obj);
JSONArray lang = (JSONArray) jsonObject.get("Headlines");
for (int i = 0; i < lang.size(); i++) {
JSONObject jsonobject = (JSONObject) lang.get(i);
Object subArray = jsonobject.get("Tags");
ObjectMapper mapperNew = new ObjectMapper();
JsonFactory factoryNew = mapperNew.getJsonFactory();
JsonParser jpNew;
System.out.println("sub Array " + subArray.toString());
jpNew = factoryNew.createJsonParser(subArray.toString());
JsonNode inputNew = mapperNew.readTree(jpNew);
for (final JsonNode elementNew : inputNew) {
Iterator<Map.Entry<String, JsonNode>> nodeIterator3 = elementNew.getFields();
while (nodeIterator3.hasNext()) {
Map.Entry<String, JsonNode> entry3 = (Map.Entry<String, JsonNode>) nodeIterator3.next();
if (entry3.getKey() != null && entry3.getKey().equals("TagType")) {
System.out.println("TagType " + entry3.getValue());
}
if (entry3.getKey() != null && entry3.getKey().equals("TagValues")) {
System.out.println("TagValues " + entry3.getValue());
}
}
}

Parsing JSON Array with JSON OBJECT

I have some JSON with the following structure:
{"cit": [
"ALL",
"Aceh Barat",
"Aceh Besar",
"Aceh Jaya",
"Aceh Selatan",
"Aceh Tengah",
"Aceh Timur",
"Aceh Utara"]}
i have try to parsing my json like this :
JSONObject jsonObject = new JSONObject(result);
JSONArray city=jsonObject.getJSONArray("cit");
for (int j=0; j < city.length(); j++){
JSONObject cit = city.getJSONObject(j);
String kot = cit.toString(j);
kota.add(kot);
}
on post execute :
ArrayAdapter<String> SpinnerKota = new ArrayAdapter<String>(Pencarian.this, android.R.layout.simple_list_item_1, kota);
spin_kota.setAdapter(SpinnerKota);
but nothing happen, is there any wrong with my code? i hope someone can help me to solve my problem.
"cit": [ // json array cit
"ALL", // index 0 is ALL
Also there is no json object inside json array cit. So you don't need this JSONObject cit = city.getJSONObject(j).
Change
String kot = cit.toString(j);
To
String kot = (String) city.get(j);
Use the below
JSONObject jsonObject = new JSONObject("myjson string");
JSONArray city=jsonObject.getJSONArray("cit");
for(int i=0;i<city.length();i++)
{
String cities = (String) city.get(i);
Log.i("All Cities",cities);
kota.add(cities);
}
Do it like this
JSONArray json = jParser.getJSONFromUrl(URL);
JSONObject c = json.getJSONObject(0);
JSONArray city = c.getJSONArray("cit");
for (int j=0; j < city.length(); j++){
String kot = cit.get(j);
kota.add(kot);
}
Object obj = yourJsonResult;
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("cit");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
you can do it as following code this is tested
String jsonSource="{'cit': ['ALL','Aceh Barat','Aceh Besar','Aceh Jaya','Aceh Selatan','Aceh Tengah','Aceh Timur','Aceh Utara']}";
try {
JSONObject jsonObject=new JSONObject(jsonSource);
JSONArray jsonArray=jsonObject.getJSONArray("cit");
int length = jsonArray.length();
String [] cities = new String [length];
if (length > 0) {
for (int i = 0; i < length; i++) {
cities[i] = jsonArray.getString(i);
}
}
//to check we can print our string array
for (int i = 0; i < cities.length; i++) {
Log.d("JSON parsing ",cities[i]);
}
} catch (JSONException e) {
e.printStackTrace();
}

Categories

Resources