在同一类的方法中使用变量而不将其作为实参或参数发送

问题描述 投票:0回答:1

text我想读取json文件并单独获取字符串中的值并将其传递到Web应用程序字段。下面是我试图执行的程序。在 readfile 方法中,我正在解析 json 文件并将其返回到 JSONArray 中。现在我只想从带有参数 ID(数组索引)的数组中获取昵称。例如 getnickname(0) 给出其他索引昵称。但参数中只提供了 id。我尝试过提供数组作为参数,并且能够实现我的目标。但我怎样才能只用 ID 参数来做到这一点。

`- 节目: 打包json程序;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.openqa.selenium.WebDriver;

public class FieldLocator {

public static WebDriver driver;
public static Object obj;
public static JSONObject jo;
//public static JSONArray address;
String baseUrl ="https://webapps.tekstac.com/AddressBook/";

public WebDriver createDriver()
{
driver=DriverSetup.getWebDriver();
driver.get(baseUrl);
return driver;
}

public JSONArray ReadFile(String FileName) throws IOException, ParseException
{
JSONParser parser=new JSONParser();
FileReader reader=new FileReader(FileName);
JSONObject obj=(JSONObject) parser.parse(reader);
String cover=(String) obj.get("cover");
System.out.println(cover);
JSONArray array=(JSONArray) obj.get("Addresses");
JSONArray address=new JSONArray();
for(int i=0;i<array.size();i++)
{
JSONObject jobj= (JSONObject) array.get(i);
address.add(i, jobj);
}
System.out.println(address);
return address; 
}

public String getNickName(int id)
{   
//i have to write the code to fetch the nickname from array
}
public String getContactName(int id)
{   
//i have to write the code to fetch the contact name from array
}
public String getCity(int id)
{   
//i have to write the code to fetch the city from array
}
public String getType(int id)
{   
//i have to write the code to fetch the Type from array
}

public static void main(String[] args) throws IOException, ParseException 
{
FieldLocator fl=new FieldLocator();
String Filename="D:\\Exercise\\Teksatc\\src\\main\\java\\jsonprogram\\AddressBook.json";        
JSONArray result=fl.ReadFile(Filename);
int count=result.size();
System.out.println(count);
for(int j=0;j<count;j++)
{
String nname=fl.getNickName(j);
System.out.println(nname);
}
}
}

**JSON 文件:** { "cover": "通讯录", “地址”: [ { “id”:“1”, “昵称”:“拉胡尔”, “联系人姓名”:“德拉维德”, "公司":"板球", "城市":"印多尔", “国家”:“印度”, “类型”:“地址” }, { “id”:“2”, “昵称”:“萨钦”, “联系人姓名”:“Tendulkar”, "公司":"板球", "城市":"孟买", “国家”:“印度”, “类型”:“地址” } ] }

请填写您的意见/意见。

我不确定这怎么可能。所以我不知道尝试多种方法。

java json methods parameters arguments
1个回答
0
投票

将您想要在程序之间传输的任何变量设置为全局变量。因此,在您的情况下,将一个数组作为全局变量(就像您注释掉的那个一样)。在 readFile 方法中,将数组存储在该全局变量中。然后你就可以在任何地方访问它。例如,在 getnickname(int id) 方法中,您可以简单地返回地址[id]。

© www.soinside.com 2019 - 2024. All rights reserved.