JSON parsing Issues Redux - java

I had issues in the past with parsing my JSON code, and I almost had it and lost all my code changes. I am putting here the guts of it getting my JSON (which I have verified it gets fine). It's just the parsing of it...I need to get the "fulltext" field and I guess put it into an array...
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
sb.append(line + "\n");
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag" , "Error converting result " + e.toString());
}
try{
JSONObject rootobject = new JSONObject(result).getJSONObject("query").getJSONObject("results");
} catch (JSONException e){
Log.e("JSON Parser", Log.getStackTraceString(e));
e.printStackTrace();
}
return null;
Within this, the JSONObject area I believe is incorrect. I need to iterate over all of the JSON objects getting the "fulltext" value from all of them and eventually putting them into the database. I'm drawing the team names from this website.
In my mind, I should be able to use
String teamname = rootobject.getString("fulltext");
in some way. I have tried this, but it doesn't work at all. In fact I get the error message "No value for fulltext" when I check the error logs.
I know I'm going wrong somewhere but can't quite place it. I'm still confused with JSON parsing and whatnot but I'm determined to get there.
This is a link to the sample JSON (the URL that I'm accessing)
http://bit.ly/1JnlSck
My apologies for forgetting this in the first post.

What you probably should do is restructure your JSON. Currently you have it like this...
"results": {
"Team:\"Die Unglaublichen\"": {
"printouts": [],
"fulltext": "Team:\"Die Unglaublichen\"",
"fullurl": "http://wiki.planetkubb.com/wiki/Team:%22Die_Unglaublichen%22",
"namespace": 822,
"exists": true
},
"Team:(Can't Stand) Le Kubb Bricks": {
"printouts": [],
"fulltext": "Team:(Can't Stand) Le Kubb Bricks",
"fullurl": "http://wiki.planetkubb.com/wiki/Team:(Can%27t_Stand)_Le_Kubb_Bricks",
"namespace": 822,
"exists": true
}
}
... where "results" is a JSONObject containing several child JSONObjects. If you can rework it so that "results" is a JSONArray containing JSONObjects, like so...
"results": [
{
"Team": "Die Unglaublichen",
"printouts": [],
"fulltext": "Team:\"Die Unglaublichen\"",
"fullurl": "http://wiki.planetkubb.com/wiki/Team:%22Die_Unglaublichen%22",
"namespace": 822,
"exists": true
},
{
"Team": "(Can't Stand) Le Kubb Bricks",
"printouts": [],
"fulltext": "Team:(Can't Stand) Le Kubb Bricks",
"fullurl": "http://wiki.planetkubb.com/wiki/Team:(Can%27t_Stand)_Le_Kubb_Bricks",
"namespace": 822,
"exists": true
}
]
... then you can loop through the "results" array and get each of its JSONObjects and any name/values you wish:
try {
JSONArray resultsArray = rootObject.getJSONArray("results");
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject teamObject = resultsArray.getJSONObject(i);
String fullText = teamObject.getString("fulltext");
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

Not sure why it has to say not valid Json after replacing the values of paymentKey and Session key

I am trying to read a json file and after traversing to attrib`s called "paymentKey" and "Session key" and changing their values through JSONObject , the post operation failing.
When i checked the out json after performing above changes it seems that structure is bit unordered , changed and even got to learn that json is not an valid one.
This is bit annoying and not sure how to keep the json format in tag after replacing the attrib`s values.
Below is the Json used
{
"idempotentId": "133215472229",
"customerId": "12345",
"brandId": "ANCHOR",
"sellingChannel": "WEBOA",
"items": [
{
"lineItemId": 123,
"productId": "ANCHOR-WEBOA-640213214",
"price": 1.19,
"quantity": 1,
"modifierGroups": [],
"childItems": [],
"note": " Drink without snacks"
}
],
"fulfillment": {
"email": "12#gmail.com",
"phoneNumber": "+912222621",
"fulfillmentType": "PickUp",
"asap": true,
"pickupFirstName": "Kiran",
"pickupLastName": "Kumar",
"locationId": "33211111"
},
"payment": {
"paymentKey": "12222-444-555-2222-44444121e",
"sessionKey": "02f3waAjHJnVCTstOIu0jcSZfm_1HnGum1lZdsu6iDlLxxjO1FYsG9DHz9130ZzMMkjYY9j5w.7V8CijbmiPSo5ESDsq5hsQ.RpYSS5wkgoSSOMjktEyDTHZh1IPq0wNayp--DE3HE53uUgTEehCvHjSsUP5q8U2ZN1kZXbsufwm_mRCV8hLCrmWVTchhVUTJtmEpyYy142DtSp1ikXOVzGN5i9z_oP5e79QvgmU7_n1C5DeARFRagQClT87vUFBUfleSbLaRyH5v3wkU7ji9URUetcq1iAfS5-cNt6-uJaulFJc2y6uNdn0OtjIe74Hp5G7Gx54VYggduoqx5X1rsCssobfUSJUDLt_vVpz5BvhQM88EaysMAB6EcQHoOnZd_YWrz4IDAAZSwSBUFQAkypVmHo5pbvp64cTDrZE73EYkEwJLGf0dRmedMFe2HiU3DiCr97K3I3KuufxYM_eMRIcn739dntxTq4QePtFdqYGWBzXWQutvvqxWQPbNi7PG_-aauEOzlwJiXG94C8t7NGu0SjB8xHf11Z3orf5Ni4-fRKugY8VJNBl39hnb4-d-g47ut7iuiFDkDHJzlSgt9LFq__CxShG_.YkL2w7QEU85VHjpOj5urieCr4-G"
},
"subTotal": 100.19,
"tax": 4.19
}
Below is the snippet of the code
import org.json.JSONObject;
import org.json.JSONArray;
public JSONObject constructCreateOrderPayload( String freedomPayPaymentKey,String orderInit_SessionKey, String payloadFile) {
String filepath = System.getProperty("user.dir")+"/src/test/resources/JsonFiles/"+payloadFile;
try {
String jsonContents = new String((Files.readAllBytes(Paths.get(filepath))));
JSONObject jsonObject = new JSONObject(jsonContents);
JSONObject payment_obj = (JSONObject) jsonObject.get("payment");
payment_obj.put("paymentKey", freedomPayPaymentKey);
payment_obj.put("sessionKey",orderInit_SessionKey);
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
System.out.println( " After Changes in JSON OBJECT : ");
System.out.println(jsonObject.toString());
System.out.println("");
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
payload = jsonObject; // when i print the json boject the format is displaced hence when validated it says invalid json
} catch (IOException e) {
System.out.println("No file found in the path ");
e.printStackTrace();
}
return payload;
}
When I validated the Json after changes it shows as invalid with errors as shown in below snapshot
I tried a lot but no success, can somebody please look in to issue and advise me where I am going wrong or provide an solution this issue.
JSON in unordered, When you print jsonObject before making the changes you will know the order of the JSON is changed, I have used the Jackson Databind libraries and below is a working code, Change it accordingly
String filepath = "C:\\Users\\wilfred\\Desktop\\Input.json";
try {
String jsonContents = new String((Files.readAllBytes(Paths.get(filepath))));
ObjectMapper mapper = new ObjectMapper();
JsonNode expected = mapper.readTree(jsonContents);
System.out.println("Before converting : " + expected.toString());
JsonNode payment_obj = (expected.get("payment"));
((ObjectNode) payment_obj).put("paymentKey", "Trial1");
((ObjectNode) payment_obj).put("sessionKey", "Trial2");
System.out.println("After converting : " + expected.toString());
} catch (IOException e) {
System.out.println("No file found in the path ");
e.printStackTrace();
}
}
My approach was correct. The only mistake was i had not supply/pass on the correct values to few of the JSon attributes and that resulted in error response.
Rectified as per requirements and was able to get results correctly, hence closing this.

Android: Parsing JSONArray of a JSONObject but still get syntax Error

i've read alot about parsing json in android and i don't know where i missed because i thinks that i do it right but it's keep showing me error
Here is my JSON:
{
"categories": [
{
"id": 1,
"category_name": "Kiehn, Kohler and Russel",
"created_at": "2018-08-29 05:35:50",
"updated_at": "2018-08-29 05:35:50"
},
{
"id": 2,
"category_name": "Flatley PLC",
"created_at": "2018-08-29 05:35:50",
"updated_at": "2018-08-29 05:35:50"
}]
}
And here is my handle in android
try {
ArrayList<TagModel> tagdata = new ArrayList<>();
JSONObject object = new JSONObject(response);
//Category
ArrayList<CategoryModel> catedata = new ArrayList<>();
JSONArray catearray = object.getJSONArray("categories");
for (int i = 0; i < catearray.length(); i++) {
JSONObject product = catearray.getJSONObject(i);
CategoryModel recommend_model = new CategoryModel();
recommend_model.setCategoryName(product.getString("category_name"));
recommend_model.setCategoryId(String.valueOf(product.getInt("id")));
catedata.add(recommend_model);
}
} catch (JSONException e) {
e.printStackTrace();
}
The Error keep telling the same issue that is:
at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
at org.json.JSONTokener.readObject(JSONTokener.java:393)
at org.json.JSONTokener.nextValue(JSONTokener.java:100)
at org.json.JSONObject.(JSONObject.java:159)
at org.json.JSONObject.(JSONObject.java:176)
at kh.com.example.sopheak_pc.CenturyRecipe.Data.DataClass$1.onResponse(DataClass.java:44)
08-30 06:47:37.283 22712-22712/kh.com.example.sopheak_pc.CenturyRecipe
W/System.err: at
kh.com.example.sopheak_pc.CenturyRecipe.Data.DataClass$1.onResponse(DataClass.java:38)
Here is the full log message:
and when i debug, the error start from
JSONObject object = new JSONObject(response);
and it's going to
catch (JSONException e) {
e.printStackTrace();
}
Sorry if it's a bit messy because i want to show everywhere that relate to the error Thanks you!!!
i've just found my error inside string json and here what it's look like
As #Andreas and #Sam Littlefair mention is my json contain "," inside the string so i clean up my data and enter simple data and it's working fine now! Thanks you 2 of you!

Reading json file with multiple objects in java

I have written a program that reads a simple json file:
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
JSONArray a = (JSONArray) parser.parse(new FileReader("C:/Users/Zonoid/Desktop/EQ.json"));
for (Object o : a)
{
JSONObject obj = (JSONObject) o;
String city = (String) obj.get("CITY");
System.out.println("City : " + city);
String loc = (String) obj.get("LOCATION");
System.out.println("Location : " + loc);
long el = (Long) obj.get("E_LEVEL");
System.out.println("Emergency Level : " + el);
long depth = (Long) obj.get("DEPTH");
System.out.println("Depth : " + depth);
long i = (Long) obj.get("INTENSITY");
System.out.println("Intensity :"+i);
System.out.println("\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
with my json file being:
[{"CITY":"MUMBAI","LOCATION":"a" ,"E_LEVEL": 6,"DEPTH":10,"INTENSITY":5},
{"CITY":"MUMBAI","LOCATION":"b" ,"E_LEVEL": 8,"DEPTH":20,"INTENSITY":4},
{"CITY":"MUMBAI","LOCATION":"c" ,"E_LEVEL": 3,"DEPTH":13,"INTENSITY":5},
{"CITY":"MUMBAI","LOCATION":"d" ,"E_LEVEL": 6,"DEPTH":12,"INTENSITY":4},]
I am working on a project that deals with earthquake alerts and want to read their JSON files however I cannot import them in JSON Array. The file I want to import looks like this:
{
"type": "FeatureCollection",
"metadata": {
"generated": 1488472809000,
"url": "https:\/\/earthquake.usgs.gov\/earthquakes\/feed\/v1.0\/summary\/significant_week.geojson",
"title": "USGS Significant Earthquakes, Past Week",
"status": 200,
"api": "1.5.4",
"count": 2
},
"features": [
{
"type": "Feature",
"properties": {
"mag": 5.5,
"place": "42km WSW of Anchor Point, Alaska",
"time": 1488420690658,....
Please tell what changes should be made.
If you are trying to read from features only, first you need to read the whole file as an object. Then you can, read the array part in the following way:
Object object = parser.parse(new FileReader("C:/Users/Zonoid/Desktop/EQ.json"));
JSONObject jasonObject = (JSONObject) object;
JSONArray features = (JSONArray) jasonObject.get("features");

How to properly convert java object to Json (Nested)

Okay so the output I would like to get is this:
{
"id": 460,
"position": {
"x": 3078,
"y": 3251,
"z": 0
},
"random-walk": true,
"walk-radius": 1
},
But the one I currently get is:
{
"id": 460,
"position": "{
"x": 3078,
"y": 3251,
"z": 0
}",
"random-walk": true,
"walk-radius": 0
},
The problem is the position object that I am trying to convert to json.
The code I tried:
Path path = Paths.get("./npcs.json");
File file = path.toFile();
file.getParentFile().setWritable(true);
if (!file.getParentFile().exists()) {
try {
file.getParentFile().mkdirs();
} catch (SecurityException e) {
System.out.println("Unable to create directory for donator data!");
}
}
try (FileWriter writer = new FileWriter(file)) {
Gson builder = new GsonBuilder().setPrettyPrinting().create();
JsonObject object = new JsonObject();
Position pos = new Position(mob.absX, mob.absY, mob.heightLevel);
object.addProperty("id", mob.npcId);
object.addProperty("position", builder.toJson(pos));
object.addProperty("random-walk", mob.randomWalk);
object.addProperty("walk-radius", mob.walkingType);
writer.write(builder.toJson(object));
writer.close();
} catch (Exception e) {
System.out.println("Something went wrong with saving for mob !");
e.printStackTrace();
}
Does anyone has a clue on how to get the first result? So without the double-quotes.
Use this
object.add("position", new Gson().toJsonTree(pos));
instead of
object.addProperty("position", builder.toJson(pos));
result should than look like this:
"position": {
"x": 10,
"y": 50
},
JSONObject json = new JSONObject();
JSONArray addresses = new JSONArray();
JSONObject address;
try
{
int count = 15;
for (int i=0 ; i<count ; i++)
{
address = new JSONObject();
address.put("Name","Name no." + i);
address.put("Country", "Country no." + i);
addresses.put(address);
}
json.put("Addresses", addresses);
}
catch (JSONException jse)
{
out.println("Error during json formatting" + jse.getMessage());
}
I would recommend using a JSONObject for your main JSON. After that, add each of the components. For a vector, add a json array. Here is a simple example I used to understand this better.
You can use your own java objects to be precise. Gson accesses the fields in your class using reflection, so you won't have to parse anything manually.
For example in your case:
import com.google.gson.annotations.SerializedName;
public class Walk {
private int id;
private Position position;
#SerializedName("random-walk")
private boolean randomWalk;
#SerializedName("walk-radius")
private int walkRadius;
}
public class Position {
private int x,y,z;
}
Then use
Gson gson = new Gson();
Walk walk = gson.fromJson(yourJson, Walk.class);

"No value for" exception for getJSONArray

I have a JSON object like this :
{
"Successful": true,
"Value": {
"Materials":[{
"MaterialID": 37628,
"MaterialID": 0,
"MaterialNo": 26868,
"Type": 0,
"MaterialName": Copper
}],
"Prices": []
}
}
I'm trying to get materials array like this :
public ArrayList<Material> parseMaterial (JSONObject object)
{
try
{
JSONArray materialArray = object.getJSONArray("Materials");
}
catch (JSONException e)
{
Log.d("JSONParser=>parseMaterial", e.getMessage());
}
}
I get this exception :
JSONParser=>parseMaterial﹕ No value for Materials
Can you tell me what is wrong with the code? Thanks.
You're missing a step: change
JSONArray materialArray = object.getJSONArray("Materials");
to
JSONObject value = object.getJSONObject("Value");
JSONArray materialArray = value.getJSONArray("Materials");
getJSONArray does not 'search' the entire object (this could give unpredictable results if you have multiple Materials in the object), only the first level.

Categories