如何从test.properties中读取json数据,其中存在其他webelements

时间:2017-08-04 06:17:36

标签: java json

我在test.properties文件中有一些WebElements,我需要读取并存储该文件中的所有json数据。任何人都可以帮助从java中的属性文件中读取所有json数据。

我已经尝试过一直阅读和存储数据,但没有运气。

以下是属性文件中的webElements:

mprHomePageLogo=//span[@class='si mpr-logo-h40px' and text()='MyPerfectResume.com']
mprHomePageLogoNewLP=//*[@class='inner-container']/span[@class='logo']
textLabel1=//*[@id='mt_mac_headline']/h1[text()='The Online Resume Builder So Easy to Use']
headingTextLabelOnNewLP=//*[contains(@class,'h1') and contains(text(),'Your Resume, Made')]/../h1/span[text()='Easy']
textLabel2=//*[text()='My Perfect Resume takes the hassle out of resume writing. Easy prompts help you create the perfect job-worthy resume effortlessly!']
desktoplikeImageOnLP=//object[contains(@class,'hero-desktop')]/following-sibling::a
iconsAndArrows=//*[@id='page-header-ctnr']/ul/li[@id="icon1" and @class="icon-ctnr"]/following-sibling::li[@id="arrow1" and @class="arrow-ctnr"]/following-sibling::li[@id="icon2" and @class="icon-ctnr"]/following-sibling::li[@id="arrow2" and @class="arrow-ctnr"]/following-sibling::li[@id="icon3" and @class="icon-ctnr"]
jsonArray= {"card":[{"Name":"1test1","place":"1placetest1"},{"Name":"2test2","place":"placetest2"},{"Name":"3test3","place":"3placetest3"}]}
textLabel3532=//*[text()='My Perfect Resume takes the hassle out of resume writing. Easy prompts help you create the perfect job-worthy resume effortlessly!']
desktoplikeImageOtestnLP=//object[contains(@class,'hero-desktop')]/following-sibling::a
jsonArray2= {"card":[{"Name":"test1","place":"placetest1"},{"Name":"test2","place":"placetest2"},{"Name":"test3","place":"placetest3"}]}

正如您所看到的,此属性文件中有两个json数据(jsonArray& jsonArray2),我需要读取此jsonArray的所有键和值。

2 个答案:

答案 0 :(得分:0)

首先,您需要从文件中读取值。这可以使用标准java软件包

使用以下代码完成
try {
        Properties prop = new Properties();
        String propFileName = "test.properties";
        inputSecretStream = getClass().getClassLoader().getResourceAsStream(propFileName);
        if (inputSecretStream != null) {
            prop.load(inputSecretStream);
        } else {
            throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
        }

        String jsonArray = prop.getProperty("jsonArray");
        String jsonArray2= prop.getProperty("jsonArray2");
    } catch (Exception e) {
        System.out.println("Exception: " + e);
    } finally {
        inputSecretStream.close();
    }

然后你应该解析你的JSON。我正在使用Google的库Gson。它应该看起来像这样

        JsonArray jarray = new JsonParser().parse(jsonArray ).getAsJsonArray();
        JsonObject jobject = jarray.getAsJsonObject("Name");

答案 1 :(得分:0)

@Ravi : you need gjson lib to parse the json data as @Sympth explained in above solution. 
Please find the below solution , Here I am reading data as InputFile.properties data and parsing it and storing it in HashMap.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class JsonParserUtility {

    public static void main(String[] args) {
        try {
            HashMap<String,String>jsonMap = new HashMap<String,String>();
            JsonParserUtility jsonParserUtility = new JsonParserUtility();
            String filePath = "$PLEASE PROVIDE properties file path here";
            //e.g. /Users/maheshjoshi/Desktop//InputFile.properties
            Properties prop = new Properties();
            FileInputStream input = new FileInputStream(filePath);
            // load a properties file
            if (input != null) {
                prop.load(input);
            }
            String jsonArray1 = prop.getProperty("jsonArray");
            String jsonArray2= prop.getProperty("jsonArray2");

            jsonMap.putAll(jsonParserUtility.parseJsonDataAndFetchAllValues(jsonArray1));
            jsonMap.putAll(jsonParserUtility.parseJsonDataAndFetchAllValues(jsonArray2));

            int count = 0;
            for (String key : jsonMap.keySet()) {
                count++;
                System.out.println(count+". key : "+key+" value : "+jsonMap.get(key));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * @param String : partialJsonData
     * @return hasmap with all key elements
     * */

    private  HashMap<String,String> parseJsonDataAndFetchAllValues(String partialJsonData) {
        HashMap<String,String>jsonMap = new HashMap<String,String>();
        JsonElement jelement = null;
        JsonObject jsonObject = null;
        try {
            JsonParser jsonParser = new JsonParser();
            jelement = jsonParser.parse(partialJsonData);
            jsonObject = jelement.getAsJsonObject();

            jsonObject = new JsonParser().parse(partialJsonData).getAsJsonObject();
            JsonArray jsonArray = jsonObject.getAsJsonArray("card");
            for (Object object : jsonArray) {
                JsonObject aJson = (JsonObject) object;
                String name = aJson.getAsJsonPrimitive("Name").toString().replaceAll("^\"|\"$", "");
                String place = aJson.getAsJsonPrimitive("place").toString().replaceAll("^\"|\"$", "");
                //System.out.println(name);
                //System.out.println(place);
                jsonMap.put(name, place);
            }           
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonMap;
    }

    /**
     * 
     * @param fileName
     * @return string data 
     * @throws IOException
     */
    public String readFile(String fileName) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        StringBuilder sb = null;
        try {
            sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                line = br.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            br.close();
        }
        return sb.toString();
    }
}