Shubham Jain
Shubham Jain

Reputation: 17553

How to read JSON object file using java and pass it to request

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

Upvotes: 0

Views: 4136

Answers (3)

Andr&#233; C. Andersen
Andr&#233; C. Andersen

Reputation: 9375

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.

Upvotes: 2

Ben Green
Ben Green

Reputation: 4121

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.

Upvotes: 1

Naresh
Naresh

Reputation: 643

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

Upvotes: -1

Related Questions