简体   繁体   English

如何使用Java读取JSON对象文件并将其传递给请求

[英]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=test7@gmail.com");
        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 :- Eclipse显示为提示/错误:

The method iterator() is undefined for the type JSONArray 未为JSONArray类型定义方法iterator()

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 任何人都可以给我解决上述问题的方法或其他替代方法,以便我可以从文件中读取JSON对象并将其作为请求直接传递给有效负载

Assuming you are using org.json.JSONArray objects. 假设您正在使用org.json.JSONArray对象。

Regarding the "iterator() is undefined" problem you are having. 关于您遇到的“ iterator()未定义”问题。 You're getting it because iterator() isn't defined for the JSONArray class. 之所以得到它,是因为未为JSONArray类定义iterator()

If you really want to print out the JSONArray object you can use the following: 如果您确实要打印出JSONArray对象,则可以使用以下命令:

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 未为JSONArray类型定义方法iterator()

This works because of the following toString() definition. 由于下面的toString()定义,此方法有效。 From what I understand, this produces a valid JSON string. 据我了解,这会产生一个有效的JSON字符串。 You should be able to simply use companyList.toString() in your response data. 您应该能够在响应数据中简单地使用companyList.toString() In fact, according to this page , the following is the "correct" way to serialize a JSONObject: 实际上,根据此页面 ,以下是序列化JSONObject的“正确”方法:

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

You can also loop through the objects in the JSONArray by doing the following: 您还可以通过执行以下操作遍历JSONArray中的对象:

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. 如果您知道数据类型,那么我们也可以选择其他任何一种

Using the Jackson ObjectMapper , you can read from a file like so: 使用Jackson ObjectMapper ,您可以像这样读取文件:

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. 然后,将此字符串数据添加到您的http请求中很简单。

Jackson's ObjectMapper can be used for JSON serialization/deserialization. Jackson的ObjectMapper可用于JSON序列化/反序列化。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM