/    Sign up×
Community /Pin to ProfileBookmark

java json object keys?

Hello.

I am trying to read a .json files content which work but then I need to use the json data somehow. Ive been trying to fix so i can use the json object keys but I cant get it to work. Mayebe someone can help me?

the json looks like this

[CODE]
{
“2”:{
“id”:2,
“name”: “test”
},
“6”:{
“id”:6,
“name”: “test”
},
“8”:{
“id”:8,
“name”: “test”
}
}
[/CODE]

PS: Java is VERY new for me

This is what ive done so far

[CODE][

//throws Exception


String key = “”;


FileReader file = new FileReader(“file.json”);
BufferedReader reader = new BufferedReader(file);



String line = reader.readLine();

while (line != null) {
key += line;
line = reader.readLine();
}

StringReader asd = new StringReader(key);
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(asd);

//System.out.println(json);

for (Object key1 : json.keySet()) {

String keyStr = (String)key1;
Object keyvalue = json.get(keyStr);

// this does not work at all – I want only the item which has keyStr “2”
if(keyStr == “2”) {
System.out.println(“key: “+ keyStr + ” value: ” + keyvalue);
}



}

}


/CODE]

to post a comment
Java

1 Comments(s)

Copy linkTweet thisAlerts:
@rootJun 27.2018 — JSON = JavaScript (not JAVA) Object Notation or something like that, the intended use is within a web page as a payload of data.

So you can have this as a basic flat file and use AJAX to pull the file off the server in HTML or you can send it as data when rendering a page in PHP and I am sure that the option you need, will be similar in as far as getting the data and then ... Sending it to the client for use.
×

Success!

Help @bbq1 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...