0

I am using the below code:-

import org.json.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.junit.Assert;
import org.junit.Test;  
import network.Authorization;
import network.ContentType;
import network.HTTPHelper;
import network.HTTPRequest;
import network.HTTPResponse;

import static org.junit.Assert.*;

import java.io.FileReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public void testSendPOSTRequest() {
    try {
        HTTPRequest request = new HTTPRequest();

        request.url = "https://myURL/api/products";
        request.contentType = ContentType.JSON;
        Map<String, String> authKeyValue = new HashMap<>();
        authKeyValue.put(Authorization.Type.toString(), "Token token=zkz,[email protected]");
        request.setAuthorization(authKeyValue);

        JSONParser parser = new JSONParser();
        
        try {
 
            Object obj = parser.parse(new FileReader("./src//productApi"));
 
            JSONObject jsonObject = (JSONObject) obj;
 
            String name = (String) jsonObject.get("Name");
            String author = (String) jsonObject.get("Author");
            JSONArray companyList = (JSONArray) jsonObject.get("Company List");
 
            System.out.println("Name: " + name);
            System.out.println("Author: " + author);
            System.out.println("\nCompany List:");
            Iterator<String> iterator = companyList.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        
        
        HTTPHelper helper = new HTTPHelper();
        HTTPResponse response = helper.sendPOSTRequest(request);
        
        System.out.println("POST Success");
        System.out.println("Response code: " +response.statusCode.toString());
        System.out.println("Payload: " +response.payload);
        assertTrue(true);
        
    } catch (Exception e) {
        System.out.println(""+e.getMessage());
        assertTrue(false);
    } finally {
        System.out.println("Exist Run");    
    }

I am also getting error in below line:-

  Iterator<String> iterator = companyList.iterator();

Eclipse showing as tips/error as :-

The method iterator() is undefined for the type JSONArray

Add to cast to

Can anyone give me a solution of above problem or any alternative way so I can read a JSON object from file and pass it directly to payload as request

7
  • I'd use some specialized library like gson or Jackson to map your JSON into a bean Commented Mar 18, 2016 at 10:02
  • I have an example using the apache http client. Will that be ok? Commented Mar 18, 2016 at 10:03
  • Why would it be necessary to read the content of the JSON first? If you just want to send the content of the file, why not just do that? I'm sure that the HTTP library you're using, can do that out of the box. But you haven't told us, which HTTP library you're using, so I can't tell you any details. Commented Mar 18, 2016 at 10:13
  • @BenGreen -> I just want to read the JSON object from file and want to pass it to payload as request.. if it is working the same the please share Commented Mar 18, 2016 at 10:22
  • @toKrause -> I have also added all the import for the same reason .. If you want some more addtional info which I am missing them please let me know Commented Mar 18, 2016 at 10:23

3 Answers 3

2

Assuming you are using org.json.JSONArray objects.

Regarding the "iterator() is undefined" problem you are having. You're getting it because iterator() isn't defined for the JSONArray class.

If you really want to print out the JSONArray object you can use the following:

System.out.println(companyList);

Instead of

Iterator<String> iterator = companyList.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

This should remove the error:

The method iterator() is undefined for the type JSONArray

This works because of the following toString() definition. From what I understand, this produces a valid JSON string. You should be able to simply use companyList.toString() in your response data. In fact, according to this page, the following is the "correct" way to serialize a JSONObject:

JSONObject object = ...
String json = object.toString();

You can also loop through the objects in the JSONArray by doing the following:

for(int i = 0; i < companyList.length(); i++){
    Object obj = companyList.get(i); //Then use obj for something. 
}

If you know the datatypes then you could us any of the other get alternatives as well.

Sign up to request clarification or add additional context in comments.

2 Comments

Anderson -> I have just look that my above code is giving me null here:- System.out.println("Name: " + name);
I have a file which contain my whole JSON.. I just want to read that file using java and pass that full payload to my request ..
1

Using the Jackson ObjectMapper, you can read from a file like so:

final InputStream is =
            Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
String data=null;
try {
    data = new ObjectMapper().readValue(is, String.class);
} catch (final Exception e) {
    //Handle errors
}

Then, adding this string data to your http request is trivial.

4 Comments

can you give me URL from where I can download the jar for Jackson
You can download the artifact from this page: mvnrepository.com/artifact/com.fasterxml.jackson.core/…
getting error as : - The type com.fasterxml.jackson.core.JsonParser cannot be resolved. It is indirectly referenced from required .class files
Add the jackson-core jar to the classpath also. That can be downloaded from here: mvnrepository.com/artifact/com.fasterxml.jackson.core/…
-1

Jackson's ObjectMapper can be used for JSON serialization/deserialization.

Example:

ObjectMapper objectMapper = new ObjectMapper();


String carJson =
    "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";


try {

    Car car = objectMapper.readValue(carJson, Car.class);

    System.out.println("car.brand = " + car.brand);
    System.out.println("car.doors = " + car.doors);
} catch (IOException e) {
    e.printStackTrace();
}

2 Comments

Thanks for the reply but Sorry I need to read a file from JSON file . I do not want that String carJson = "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";
I just gave an example to use ObjectMapper. readValue has many implementations. You can also read from file. Check this mkyong.com/java/how-to-convert-java-object-to-from-json-jackson

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.