Created
November 28, 2014 22:46
-
-
Save OlgaKulikova/f41c97d2592c4a6fb616 to your computer and use it in GitHub Desktop.
PersonJSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package personJson; | |
public class Address { | |
public String country; | |
public String city; | |
public String street; | |
@Override | |
public String toString() { | |
return "Country: " + country + "\n" + | |
"City: " + city + "\n" + | |
"Street: " + street + "\n"; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package personJson; | |
import java.util.Arrays; | |
public class Json { | |
public String name; | |
public String surname; | |
public String[] phones; | |
public String[] sites; | |
public Address address; | |
@Override | |
public String toString() { | |
return "Name: " + name + "\n" + | |
"Surname: " + surname + "\n" + | |
"Phones: " + Arrays.toString(phones) + "\n" + | |
"Sites: " + Arrays.toString(sites) + "\n" + | |
"Address: " + address.toString() + "\n"; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package personJson; | |
import com.google.gson.Gson; | |
import com.google.gson.GsonBuilder; | |
import java.io.IOException; | |
import java.io.RandomAccessFile; | |
import java.util.Arrays; | |
public class Main { | |
public static void main(String[] args) { | |
String path = "D:\\dir\\person.txt"; | |
String result = null; | |
try { | |
result = fileToText(path); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
Gson gson = new GsonBuilder().create(); | |
Json json = gson.fromJson(result, Json.class); | |
//Выводим на экран то, что нам нужно | |
System.out.println(json.surname + Arrays.toString(json.sites)); | |
System.out.println("----------------------------------------"); | |
//Выводим на экран все | |
System.out.println(json.toString()); | |
} | |
public static String fileToText(String path) throws IOException { | |
try (RandomAccessFile raf = new RandomAccessFile(path, "r")){ | |
byte[] buf = new byte[(int) raf.length()]; | |
raf.read(buf); | |
return new String(buf); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment