I have a junk of json that has a nested json array inside of it. What would be the best way to get that nested json out and then get the length of it. I want to get the two fields inside of "/details" then use them
{
"Lane2":[
{
"authHost":"host.com",
"action-items":[
{
"/details":[
{
"path":"/something/details",
"httpMethod":"get"
}
]
},
{
"/summary":[
{
"path":"/something/summary",
"httpMethod":"get"
}
]
},
{
"/summary":[
{
"path":"/action-items/summary",
"httpMethod":"get"
}
]
}
]
}
]
}
I agree use the JSON parser, here's a simple example if you want to try on your own:
public String[] parseJA(JSONArray input, String[] key) throws JSONException{
// Parses a JSONArray with matching KEY value into a Sring[]
output = new String[input.length()];
joOutput = new JSONObject[input.length()];
for(int i = 0; i < input.length();++i) {
output[i] = input.getString(i);
joOutput[i] = input.getJSONObject(i);
output[i] = joOutput[i].getString(key[i]);
}
return output;
}
Related
I'm New to android development. I just know very little about JSON. I used Json simple format.
{
"worldpopulation":
[
{
"rank":1,"country":"China",
"population":"1,354,040,000",
"flag":"http://www.androidbegin.com/tutorial/flag/china.png"
},
{
"rank":2,"country":"India",
"population":"1,210,193,422",
"flag":"http://www.androidbegin.com/tutorial/flag/india.png"
}
]
}
In above JSON data we can simply call rank, country after getting JSOn array worldpopulation.
Now I have JSON data showed below, here JSON array is same I think since item is present I don't know. Then it has objects as numbers under that it has country.
{
"Items":"0 to 2",
"worldpopulation":[
{
"0":{
"country":"China",
"population":"1,354,040,000",
"flag":"http://www.androidbegin.com/tutorial/flag/china.png"
}
},
{
"1":{
"country":"India",
"population":"1,210,193,422",
"flag":"http://www.androidbegin.com/tutorial/flag/india.png"
}
}
]
}
Now I don't know how to call country, population and flag.
Is it same method as. Jsonobject.getstring("rank"); after jsonarray("worldpopulation");
Or different.
Do as following
try {
JSONObject reader = new JSONObject("your json str");
JSONArray items = reader.getJSONArray("worldpopulation");
for (int i = 0; i < items.length(); ++i) {
JSONObject jsonProgram = items.getJSONObject(i);
JSONObject yourObject = null;
if (i == 0) {
yourObject = jsonProgram.getJSONObject("0");
} else {
yourObject = jsonProgram.getJSONObject("1");
}
//Do here what did before with yourObject
}
} catch (JSONException e) {
Log.i("Test", e.toString());
}
I have an array "myarray" like this:
[{
name: John,
age: {
years:18
},
computer_skills: {
years:4
},
mile_runner: {
years:2
}
}]
How do I uplevel it properly? Using minimal-json, I do the following:
JsonArray jsonArray = JsonArray.readFrom(myarray);
for( JsonValue val : jsonArray) {
JsonObject myObj = val.asObject();
for( JsonObject.Member myMember : myObj ) {
if(myMember.getValue().isObject()) {
JsonObject myMemberObj = myMember.getValue().asObject();
for (JsonObject.Member nestedMember : myMemberObj) {
if(nestedMember.getName().equals("years")) {
myObj.set(myMember.getName(), nestedMember.getValue());
break;
}
}
}
}
}
System.out.println(jsonArray);
The last line when I print out my jsonArray, it looks as if nothing has changed whatsoever. What am I doing wrong? I want to end up with the following:
[{
name: John,
age: 18
computer_skills: 4
mile_runner: 2
}]
I tried using this: https://github.com/ralfstx/minimal-json. Alternatives are welcome. I want to not have to create a model object that contains key value pairs for every single key value in my object within "myarray". I am used to python where everything is simple to access and replace.
After some researching I found out that your json array is invalid, there are quotes missing on at least the keys (See why do you need the quotes). Look at the same code you used but with modified input for 'myarray':
String myarray = "[{\"name\":\"John\",\"age\":{\"years\":18},\"computer_skills\":{\"years\":4},\"mile_runner\":{\"years\":2}}]";
JsonArray jsonArray = JsonArray.readFrom(myarray);
for( JsonValue val : jsonArray) {
JsonObject myObj = val.asObject();
for( JsonObject.Member myMember : myObj ) {
if(myMember.getValue().isObject()) {
JsonObject myMemberObj = myMember.getValue().asObject();
for (JsonObject.Member nestedMember : myMemberObj) {
if(nestedMember.getName().equals("years")) {
myObj.set(myMember.getName(), nestedMember.getValue());
break;
}
}
}
}
}
System.out.println(jsonArray);
This code prints:
[{"name":"John","age":18,"computer_skills":4,"mile_runner":2}]
what is the expected result.
I have a JSON Object of the following and I need to parse the path strings inside the web array into an new JSON array.
"taxonomy": {
"source": {
"master": {
"_id": "5000",
"path": "/Appliances/Refrigerators/French Door Bottom Freezers"
},
"web": [
{
"_id": "6686",
"path": "/Appliances/Refrigerators/French Door Bottom Freezers"
},
{
"_id": "7686",
"path": "/Appliances/Refrigerators/Bottom Freezers"
}
],
},
},
I have written till this but I'm not sure how to get all the path inside the web array.
JSONObject jsonTaxonomy= _blob.optJSONObject("taxonomy");
if(jsonTaxonomy!=null)
{
if(!jsonTaxonomy.isNull("source"))
{
JSONObject jsonTaxonomySource= jsonTaxonomy.optJSONObject("source");
if(!jsonTaxonomySource.isNull("web"))
{
JSONArray jsonTaxonomySourceWeb= jsonTaxonomySource.optJSONArray("web");
if(jsonTaxonomySourceWeb!=null && jsonTaxonomySourceWeb.length()>0)
{
//Got inside the array
}
}
}
}
Without providing you with a full answer, I'm convinced you'll be able to find your answer by debugging this method and stopping it at the most inner if(). You'll be able to of what jsonTaxonomySearsWeb consists and thus how to get its values.
Modify your code to something like this:-
JSONObject jsonTaxonomy= _blob.optJSONObject("taxonomy");
if(jsonTaxonomy!=null)
{
JSONObject jsonTaxonomySource = jsonTaxonomy.optJSONObject("source");
if(jsonTaxonomySource!=null)
{
JSONArray jsonTaxonomySearsWeb= jsonTaxonomySource.optJSONArray("web");
if(jsonTaxonomySearsWeb!=null)
{
// Traverse through your JSONArray and get each Object & extract path from it.
}
}
}
I am bit unclear about the question. But As per my understanding you want to parse the JSON if you want to do that in java then you can use GSON jar from google...you can also check simple example here Gson handle object or array
Try like this...
groups = json.getJSONArray(TAG_GROUP);
System.out.println("Result Success+++"+groups);
for (int i = 0; i < groups.length(); i++) {
JSONObject c = groups.getJSONObject(i);
String source = c.getString(TAG_SOURCE);
System.out.println("Checking ::"+source);
String lname = c.getString(TAG_PATH);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_SOURCE, source);
map.put(TAG_PATH,path);
weblist.add(map); //weblist is your arraylist for both values
webpathlist.add(path); //webpathlist is your arraylist for path
}
List<String> newList = new ArrayList<String>();
newList.addAll(weblist);
I am fairly new to JSON parser and I am trying to extract all data set from "sizes" tag i.e extracting values (small, yes, xsmall, NO, Medium and yes) from the JSON file in a complex nested loop but doesn't work. I am using GSON to parse the JSON file and using JAVA as programming language
Here how the JSON file looks like in general
{ response: "ok",
prodinfo: {
sizes: [
{ size:"small",
available: "yes"
},
{ size:"xsmall",
available: "No"
},
{ size:"Medium",
available: "yes"
}
]
}
}
This is what i did
int array = jsonParser14.parse(json14).getAsJsonObject().get("ProdInfo").getAsJsonObject().getAsJsonArray("sizes").size();
JsonArray sizes = (JsonArray) jsonParser15.parse(json15).getAsJsonObject().get("ProdInfo").getAsJsonObject().getAsJsonArray("sizes");
for (int i = 0; i <= array; i++) {
String size = sizes.get(i).getAsString();
System.out.println("data extracted are: " + size);
}
Your help will be appreciated.
Thanks
I usually treat this by making a public class with required fields :
public class ProdSize {
public String size;
public String available;
}
public class ProdInfo {
public ProdSize[] sizes;
}
public class Message {
public String response;
public ProdInfo prodinfo;
}
And then I just have to do this in gson :
Gson gson = new GsonBuilder().create();
Message mess = gson.fromJson(theJsonString, Message.class);
Then, I don't have any loop to do to parse the JSON. I directly have my sizes in
mess.prodinfo.sizes
For example you can print them like this
for (int i=0; i<mess.prodinfo.sizes.length; i++) {
ProdSize size = mess.prodinfo.sizes[i];
System.out.println("Size " + size.size + " -> " + size.available);
}
Something like:
var sizes = json.prodinfo.sizes;
for (item in sizes) {
if (sizes.hasOwnProperty(item)) {
var isAvailable = sizes[item].available;
alert(isAvailable);
}
}
Example here: http://jsfiddle.net/nG88B/3/
Edit:
Looks like you need to parse the JSON first. In which case (if it's valid) you can do:
var obj = JSON.parse(jsonStr);
I'm trying to convert a very complex array structure to a JSON object, but I'm not sure how to work with the conversion. The structure is as follows:
String[] foo = new String[10];
String[][] bar = new String[10][8];
String[][] blargh = new String[8][2];
// Populate foo
foo[0] = "foo1";
// ... and so on
bar[0][0] = "bar1";
// ... and so on
blargh[0][0] = "blargh1;"
// ... and so on
Then:
public JSONObject createJSONObject() {
/* Now, I would like to create an object with the structue:
[{
foo[0] : {
bar[0][0] : {
// more key-pair values, including blargh[0][0] and blargh[0][1]
},
bar[0][1] : {
// values of blargh[1][0] and blargh[1][1]
},
// etc...
},
foo[1] : {
bar[1][0] : {
/* primary index of bar will always match index of foo, as will the primary index of blargh */
},
// etc..
},
// etc..
}]
// return the JSON encoded object
}
This seems reasonably complex to me, so please tell me if my question/code/structure is confusing or not clear.
Break it down into manageable chunks. Create methods that understand how to construct each nested object individually, and then call them at the appropriate times. For instance, something like:
public JSONObject createJSONObject() {
JSONObject result = new JSONObject();
for (int fooIndex = 0; fooIndex < foo.length; fooIndex++) {
result.put(foo[fooIndex], createBarJsonObject(fooIndex));
}
return result;
}
private JSONObject createBarJsonObject(int index) {
JSONObject result = new JSONObject();
String[] keys = bar[index];
for (int barIndex = 0; barIndex < keys.length; barIndex++) {
result.put(keys[barIndex], createBlarghJsonObject(fooIndex));
}
return result;
}
private JSONObject createBlarghJsonObject(int index) {
JSONObject result = new JSONObject();
String[] keyValue = blargh[index];
result.put(keyValue[0], keyValue[1]);
return result;
}
You're not creating arrays, you're creating objects. There's no point in the enclosing array in your pseudo code.
Object: { key0:val0, key1:val1 }
Array: [ val0, val1, val2 ]
{ // start object
key_foo0 : // foo[0] string as a key
{ // new object as a value
key_bar0_0 :
{
key_blargh0_0: val_blargh0_1, // blargh[0][1] as value
key_bleuuw0_0: val_bleuuw0_1
}
}
} // end object