How to parse array from JsonArray? - java

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

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

How to parse JSON array from file?

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

Array inside JSONArray iteration in java

My Json is:
{
"Response": {
"Asset": [
{
"id": 2461,
"name": "TestAsset7771",
"model_name": "TestModel777",
"serial_number": "TestAsset7771",
"current_data": {
"timestamp": "",
"name": "Temperature",
"value": "?"
}
},
{
"id": 2448,
"model_id": 1229,
"name": "TestAsset777",
"model_name": "TestModel777",
"serial_number": "TestAsset777",
"current_data": {
"timestamp": "",
"name": "Temperature",
"value": "?"
}
}
]
}
}
My code is:
JSONObject outerObject = new JSONObject(jsonObj.toString());
JSONObject innerObject = outerObject.getJSONObject("Response");
JSONArray jsonArray = innerObject.getJSONArray("Asset");
for (int i = 0, size = jsonArray.length(); i < size; i++)
{
JSONObject objectInArray = jsonArray.getJSONObject(i);
String[] elementNames = JSONObject.getNames(objectInArray)
for (String elementName : elementNames)
{
String value = objectInArray.getString(elementName);
System.out.printf("name=%s, value=%s\n", elementName, value);
}
}
For inner array - ie current data, am getting values as:
name=current_data,
value={"timestamp":"","name":"Temperature","value":"?"}
How can i put another inner array so that i can get values of
"timestamp":"", "name":"Temperature", "value":"?" in separate variables instead of complete JSON
Its better to use Gson to parse JSON. Anyway, if you decide to follow as this is, try as :
You have a class like this:
class CurrentData{
String name,timestamp,value;
void print(){
System.out.printf("name=%s, timestamp=%s, value=%s\n", name,timestamp, value);
}
}
Now, change your for loop as follows:
for (String elementName : elementNames)
{
if(!elementName.equals("current_data")){
String value = objectInArray.getString(elementName);
System.out.printf("name=%s, value=%s\n", elementName, value);
}
else{
CurrentData obj=new CurrentData();// You can use array of objects declaring outside the loop as your need
JSONObject curr_object=objectInArray.getJSONObject("current_data");
obj.name=curr_object.getString("name");
obj.timestamp=curr_object.getString("timestamp");
obj.value=curr_object.getString("value");
obj.print();
}
}
for (String elementName : elementNames)
{
JSONObject jsonobject = jsonarray.getJSONObject(elementName);
System.out.printf( "name=%s, value=%s\n",jsonobject.getString("name"),jsonobject.getString("value"));
}
"value" is another jason object, so you can just call "getJasonObject()" to obtain the item and then proceed with that new array as normal.
Edit: I made a fail (not enough C0FFEE in my memory) and corrected thanks to the comment.
JSONObject outerObject = new JSONObject(jsonObj.toString());
JSONObject innerObject = outerObject.getJSONObject("Response");
JSONArray jsonArray = innerObject.getJSONArray("Asset");
for (int i = 0, size = jsonArray.length(); i < size; i++) {
JSONObject objectInArray = jsonArray.getJSONObject(i);
JSONObject currentData = objectInArray.getJSONObject("current_data");
if (currentData != null) {
String timestamp = currentData.getString("timestamp");
String name = currentData.getString("name");
String value = currentData.getString("value");
// Assign above results to array elements or whatever
}
}
//nested jsonarray
FileReader inp=new FileReader("xyz.json");
JSONParser parser=new JSONParser();
Object obj=parser.parse(inp);
JSONArray jsonArray=(JSONArray) obj;
int len=jsonArray.size();
for(i:len)
{
JSONArray json1=(JSONArray) jsonArray.get(i);
Iterato iterator=json1.iterator();
while(iterator.hasNext())
System.out.println(iterator.next());
}

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