Java Code Examples for com.badlogic.gdx.utils.Json#fromJson()

The following examples show how to use com.badlogic.gdx.utils.Json#fromJson() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HighScoreManager.java    From FruitCatcher with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void retrieveHighScores() {
	FileHandle highScoresFile = Gdx.files.local(SCORES_DATA_FILE);
	if( highScoresFile.exists() ) {
		Json json = new Json();
		try {
			String encScoresStr = highScoresFile.readString();
			String scoresStr = Base64Coder.decodeString( encScoresStr );
			highScores = json.fromJson(ArrayList.class, HighScore.class, scoresStr);
			return;
           } catch( Exception e ) {
               Gdx.app.error( HighScoreManager.class.getName(), 
               		"Unable to parse high scores data file", e );
           }
	}
	highScores = new ArrayList<HighScore>();
	String playerName = textResources.getDefaultPlayerName();
	for(int i=0;i<HIGH_SCORES_COUNT;i++){
		highScores.add(new HighScore(playerName, 50 - 10*i, false));
	}
}
 
Example 2
Source File: JsonProcessor.java    From gdx-fireapp with Apache License 2.0 6 votes vote down vote up
static <R> R process(Class<?> wantedType, String jsonString) {
    Json json = new Json();
    json.setIgnoreUnknownFields(true);
    json.setTypeName(null);
    R result = null;
    if (ClassReflection.isAssignableFrom(List.class, wantedType)
            || ClassReflection.isAssignableFrom(Map.class, wantedType)) {
        if (wantedType == List.class) {
            wantedType = ArrayList.class;
        } else if (wantedType == Map.class) {
            wantedType = HashMap.class;
        }
        json.setDefaultSerializer(new JsonListMapDeserializer(HashMap.class));
        result = (R) json.fromJson(wantedType, jsonString);
    } else {
        result = (R) json.fromJson(wantedType, jsonString);
    }
    return result;
}
 
Example 3
Source File: Config.java    From beatoraja with GNU General Public License v3.0 6 votes vote down vote up
public static Config read() {
	Config config = null;
	if (Files.exists(MainController.configpath)) {
		Json json = new Json();
		json.setIgnoreUnknownFields(true);
		try (FileReader reader = new FileReader(MainController.configpath.toFile())) {
			config = json.fromJson(Config.class, reader);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	if(config == null) {
		config = new Config();
	}
	config.validate();

	PlayerConfig.init(config);

	return config;
}
 
Example 4
Source File: HighScoreManager.java    From FruitCatcher with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static List<HighScore> deserialize(String scoresStr) {
	Json json = new Json();
	try {
		return json.fromJson(ArrayList.class, HighScore.class, scoresStr);
       } catch( Exception e ) {
           Gdx.app.error( HighScoreManager.class.getName(), 
           		"Unable to deserialize high scores", e );
       }
       return null;
}
 
Example 5
Source File: AITeamFileReader.java    From Norii with Apache License 2.0 5 votes vote down vote up
public static void loadLevelsInMemory() {
	if (!statsLoaded) {
		final Json json = new Json();
		final AITeamData[] aiTeamStats = json.fromJson(AITeamData[].class, Gdx.files.internal(LEVELS_FILE_LOCATION));
		for (int i = 0; i < aiTeamStats.length; i++) {
			final AITeamData data = aiTeamStats[i];
			aiTeamData.put(data.getId(), data);
		}
		statsLoaded = true;
	}
}
 
Example 6
Source File: CocoStudioUIEditor.java    From cocos-ui-libgdx with Apache License 2.0 5 votes vote down vote up
public static List<String> getResources(FileHandle jsonFile) {
    dirName = jsonFile.parent().toString();

    if (!dirName.equals("")) {
        dirName += File.separator;
    }
    String json = jsonFile.readString("utf-8");
    Json jj = new Json();
    jj.setIgnoreUnknownFields(true);
    CCExport export = jj.fromJson(CCExport.class, json);
    return export.getContent().getContent().getUsedResources();
}
 
Example 7
Source File: JSONSkinLoader.java    From beatoraja with GNU General Public License v3.0 5 votes vote down vote up
public SkinHeader loadHeader(Path p) {
	serializer = new JsonSkinSerializer(lua, path -> getPath(path, filemap));
	SkinHeader header = null;
	try {
		Json json = new Json();
		json.setIgnoreUnknownFields(true);
		serializer.setSerializers(json, null, p);
		sk = json.fromJson(JsonSkin.Skin.class, new FileReader(p.toFile()));
		header = loadJsonSkinHeader(sk, p);
	} catch (FileNotFoundException e) {
		Logger.getGlobal().severe("JSONスキンファイルが見つかりません : " + p.toString());
	}
	return header;
}
 
Example 8
Source File: JsonSkinSerializer.java    From beatoraja with GNU General Public License v3.0 5 votes vote down vote up
private void includeArray(Json json, JsonValue jsonValue, Class cls, ArrayList<T> items) {
	Json subJson = new Json();
	subJson.setIgnoreUnknownFields(true);
	File file = pathGetter.apply(path.getParent().toString() + "/" + jsonValue.get("include").asString());
	if (file.exists()) {
		setSerializers(subJson, this.options, file.toPath());
		try {
			T[] array = (T[])subJson.fromJson(cls, new FileReader(file));
			Collections.addAll(items, array);
		} catch (FileNotFoundException e) {
		}
	}
}
 
Example 9
Source File: PracticeConfiguration.java    From beatoraja with GNU General Public License v3.0 5 votes vote down vote up
public void create(BMSModel model) {
	property.judgerank = model.getJudgerank();
	property.endtime = model.getLastTime() + 1000;
	Path p = Paths.get("practice/" + model.getSHA256() + ".json");
	if (Files.exists(p)) {
		Json json = new Json();
		try {
			property = json.fromJson(PracticeProperty.class, new FileReader(p.toFile()));
		} catch (FileNotFoundException | SerializationException e) {
			e.printStackTrace();
		}
	}

	if(property.gaugecategory == null) {
		property.gaugecategory = BMSPlayerRule.getBMSPlayerRule(model.getMode()).gauge;
	}
	this.model = model;
	if(property.total == 0) {
		property.total = model.getTotal();
	}
	FreeTypeFontGenerator generator = new FreeTypeFontGenerator(
			Gdx.files.internal("skin/default/VL-Gothic-Regular.ttf"));
	FreeTypeFontParameter parameter = new FreeTypeFontParameter();
	parameter.size = 18;
	titlefont = generator.generateFont(parameter);
	
	for(int i = 0; i < graph.length; i++) {
		graph[i].setDestination(0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, new int[0]);
	}
}
 
Example 10
Source File: BMSSearchAccessor.java    From beatoraja with GNU General Public License v3.0 5 votes vote down vote up
public TableData read() {
	TableData td = null;
	try (InputStream input = new URL("http://qstol.info/bmssearch/api/services/?method=bms.new").openStream()) {
		Json json = new Json();
		BMSSearchElement[] elements = json.fromJson(BMSSearchElement[].class, input);
		
		td = new TableData();
		TableFolder tdenew = new TableFolder();
		tdenew.setName("New");
		List<SongData> songs = new ArrayList();
		for(BMSSearchElement element : elements) {
			if(element.getFumen() != null && element.getFumen().length > 0) {
				for(Fumen fumen : element.getFumen()) {
					SongData song = new SongData();
					song.setTitle(fumen.getTitle());
					song.setArtist(element.getArtist());
					song.setGenre(element.getGenre());
					song.setMd5(fumen.getMd5hash());
					if(element.getDladdress() != null && element.getDladdress().length > 0) {
						song.setUrl(element.getDladdress()[0]);							
					}
					songs.add(song);
				}
			} else {
				// 譜面が存在しない場合の処理はここに書く
			}
		}
		tdenew.setSong(songs.toArray(new SongData[songs.size()]));
		td.setFolder(new TableFolder[]{tdenew});
		td.setName("BMS Search");
           Logger.getGlobal().info("BMS Search取得完了");
	} catch (Throwable e) {
		Logger.getGlobal().severe("BMS Search更新中の例外:" + e.getMessage());
	}
	return td;
}
 
Example 11
Source File: PlayerConfig.java    From beatoraja with GNU General Public License v3.0 5 votes vote down vote up
public static PlayerConfig readPlayerConfig(String playerpath, String playerid) {
	PlayerConfig player = new PlayerConfig();
	try (FileReader reader = new FileReader(Paths.get(playerpath + "/" + playerid + "/config.json").toFile())) {
		Json json = new Json();
		json.setIgnoreUnknownFields(true);
		player = json.fromJson(PlayerConfig.class, reader);
		player.setId(playerid);
		player.validate();
	} catch(Throwable e) {
		e.printStackTrace();
	}
	return player;
}
 
Example 12
Source File: PlayDataAccessor.java    From beatoraja with GNU General Public License v3.0 5 votes vote down vote up
/**
 * コースリプレイデータを読み込む
 * 
 * @param hash
 *            対象のBMSハッシュ群
 * @param lnmode
 *            LNモード
 * @return リプレイデータ
 */
public ReplayData[] readReplayData(String[] hash, boolean ln, int lnmode, int index,
		CourseData.CourseDataConstraint[] constraint) {
	if (existsReplayData(hash, ln, lnmode, index, constraint)) {
		Json json = new Json();
		json.setIgnoreUnknownFields(true);
		try {
			String path = this.getReplayDataFilePath(hash, ln, lnmode, index, constraint);
			ReplayData[] result = null;
			if (Files.exists(Paths.get(path + ".brd"))) {
				result = json.fromJson(ReplayData[].class, new BufferedInputStream(
						new GZIPInputStream(Files.newInputStream(Paths.get(path + ".brd")))));
			}
			if(result != null) {
				for(ReplayData rd : result) {
					if(rd == null || !rd.validate()) {
						return null;
					}
				}
				return result;
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	return null;
}
 
Example 13
Source File: Recorder.java    From gdx-proto with Apache License 2.0 5 votes vote down vote up
private Array<Snapshot> loadJson() {
	Json json = new Json();
	String filename = demoDir + "history.json.gz";
	FileHandle histFile = Gdx.files.external(filename);
	if (!histFile.exists()) {
		Log.error("playback history file doesn't exist, skip loading: " + filename);
		return null;
	}
	byte[] bytes = histFile.readBytes();
	String data = Compression.decompressToString(bytes);
	System.out.println(data);
	return (Array<Snapshot>) json.fromJson(Array.class, data);
}
 
Example 14
Source File: NSDictionaryHelper.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
static NSDictionary toNSDictionary(Object object) {
    if (object instanceof Map) {
        return toNSDictionary((Map) object);
    } else {
        String objectJsonData = new Json().toJson(object);
        Json json = new Json();
        json.setIgnoreUnknownFields(true);
        Map objectMap = json.fromJson(HashMap.class, objectJsonData);
        return toNSDictionary(objectMap);
    }
}
 
Example 15
Source File: MapConverter.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Map<String, Object> unConvert(Object object) {
    try {
        String jsonString = new Json().toJson(object);
        Json json = new Json();
        json.setIgnoreUnknownFields(true);
        json.setTypeName(null);
        json.setQuoteLongValues(true);
        return json.fromJson(HashMap.class, jsonString);
    } catch (Exception e) {
        GdxFIRLogger.error("Can't serialize " + object.getClass().getSimpleName() + " to Map.", e);
        return null;
    }
}
 
Example 16
Source File: StateManager.java    From FruitCatcher with Apache License 2.0 5 votes vote down vote up
public StateBundle retrieveState() {
	FileHandle stateDataFile = Gdx.files.local(STATE_DATA_FILE);
	if( stateDataFile.exists() ) {
		Json json = new Json();
		try {
			String stateStr = stateDataFile.readString();
               return json.fromJson(StateBundle.class, stateStr );
           } catch( Exception e ) {
               Gdx.app.error( "StateManager", 
               		"Unable to parse existing game screen state data file", e );
           }
	}
	return null;
}
 
Example 17
Source File: EntityFileReader.java    From Norii with Apache License 2.0 5 votes vote down vote up
public static void loadUnitStatsInMemory() {
	if (!statsLoaded) {
		final Json json = new Json();
		final EntityData[] unitStats = json.fromJson(EntityData[].class, Gdx.files.internal(UNIT_STATS_FILE_LOCATION));
		for (int i = 0; i < unitStats.length; i++) {
			final EntityData data = unitStats[i];
			unitData.put(data.getID(), data);
		}
		statsLoaded = true;
	}
}
 
Example 18
Source File: SpellFileReader.java    From Norii with Apache License 2.0 5 votes vote down vote up
public static void loadSpellsInMemory() {
	if (!statsLoaded) {
		final Json json = new Json();
		final SpellData[] unitStats = json.fromJson(SpellData[].class, Gdx.files.internal(UNIT_STATS_FILE_LOCATION));
		for (int i = 0; i < unitStats.length; i++) {
			final SpellData data = unitStats[i];
			spellData.put(data.getId(), data);
		}
		statsLoaded = true;
	}
}
 
Example 19
Source File: CocoStudioUIEditor.java    From cocos-ui-libgdx with Apache License 2.0 4 votes vote down vote up
/**
 * @param jsonFile     ui编辑成生成的json文件
 * @param textureAtlas 资源文件,传入 null表示使用小文件方式加载图片.
 * @param ttfs         字体文件集合
 * @param bitmapFonts  自定义字体文件集合
 * @param defaultFont  默认ttf字体文件
 */
public CocoStudioUIEditor(FileHandle jsonFile,
                          Map<String, FileHandle> ttfs, Map<String, BitmapFont> bitmapFonts,
                          FileHandle defaultFont, Collection<TextureAtlas> textureAtlas) {
    this.textureAtlas = textureAtlas;
    this.ttfs = ttfs;
    this.bitmapFonts = bitmapFonts;
    this.defaultFont = defaultFont;
    parsers = new HashMap<>();

    addParser(new CCButton());
    addParser(new CCCheckBox());
    addParser(new CCImageView());
    addParser(new CCLabel());
    addParser(new CCLabelBMFont());
    addParser(new CCPanel());
    addParser(new CCScrollView());
    addParser(new CCTextField());
    addParser(new CCLoadingBar());
    addParser(new CCTextAtlas());

    addParser(new CCLayer());

    addParser(new CCLabelAtlas());
    addParser(new CCSpriteView());
    addParser(new CCNode());

    addParser(new CCSlider());

    addParser(new CCParticle());
    addParser(new CCProjectNode());
    addParser(new CCPageView());

    addParser(new CCTImageView());

    actors = new HashMap<String, Array<Actor>>();
    actionActors = new HashMap<Integer, Actor>();

    //animations = new HashMap<String, Map<Actor, Action>>();

    actorActionMap = new HashMap<Actor, Action>();

    dirName = jsonFile.parent().toString();

    if (!dirName.equals("")) {
        dirName += File.separator;
    }
    String json = jsonFile.readString("utf-8");
    Json jj = new Json();
    jj.setIgnoreUnknownFields(true);
    export = jj.fromJson(CCExport.class, json);
}
 
Example 20
Source File: JsonListMapDeserializer.java    From gdx-fireapp with Apache License 2.0 4 votes vote down vote up
private Object processObject(Json json, JsonValue jsonData) {
    return json.fromJson(this.objectType, jsonData.toJson(JsonWriter.OutputType.json));
}